I want to get the value of RequestType and ReceiptNumber. How can I achieve that?
From your code, it seems that you have already get the xml string, then to get the attribute value, since the RequestType
and ReceiptNumber
attribute are in the root element. You could use the XmlElement.GetAttribute Method to get the attribute value. Code like this:
var xmlstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<Trans ItemId=\"\" Type=\"Copy\" RequestType=\"testname\" Description=\"Copy 2023\" NameOnRecord=\"\" Paid=\"xxx\" Printed=\"yyyy\" Status=\"test\" VoidReason=\"\" ProcessedLocationId=\"\" ProcessedBy=\"\" ProcessedDate=\"\" ReceiptNumber=\"123123\">" +
"<Parameters>" +
"<Parameter Name=\"DocumentId\" Value=\"123456\" Type=\"1\"/>" +
"</Parameters>" +
"</Trans>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlstring);
XmlElement root = doc.DocumentElement; //get the root element.
// Check to see if the element has a RequestType and ReceiptNumber attribute.
if (root.HasAttribute("RequestType"))
{
var requesttype = root.GetAttribute("RequestType");
Console.WriteLine($"Request Type: {requesttype}");
}
if (root.HasAttribute("ReceiptNumber"))
{
var receiptnumber = root.GetAttribute("ReceiptNumber");
Console.WriteLine($"Request Type: {receiptnumber}");
}
Besides, you can also use LINQ to XML to find the element and get the attribute value (refer to How to find descendant elements (LINQ to XML)), code like this:
XDocument doc2 = XDocument.Parse(xmlstring);
var requesttype2 = doc2.Descendants("Trans").Attributes("RequestType").Select(x => x.Value).FirstOrDefault();
Console.WriteLine($"Request Type: {requesttype2}");
var receiptnumber2 = doc2.Descendants("Trans").Attributes("ReceiptNumber").Select(x => x.Value).FirstOrDefault();
Console.WriteLine($"Request Type: {receiptnumber2}");
The result as below:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion