parsing xml in C# .net core

Anjali Agarwal 1,386 Reputation points
2023-05-09T23:47:56.9266667+00:00

I am trying to parse an XMl. I am reading an XML file from the database and then I am trying to parse. below is what I have:

I am reading the records coming from the database in a List and then passing that XML as string type to another method so that I can parse that XML

result =LINQ qyery

  foreach(var r in result) 
            {

                string Type = GetTypeFromXML(r[5].ToString());
              
            }
   private string GetTypeFromXML(string xml)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml);
            // XmlNodeList parentNode = xmlDoc.GetElementById("SelfServiceTransactionItem");
            return "";
        }

GetTypeFromXML is suppose to parse the XML that is passed as a string. Below is my XML that I am passing as a string to GetTypeFromXML:

<?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="">
   <Parameters>
      <Parameter Name="DocumentId" Value="123456" Type="1"/>
     
   </Parameters>
</Trans>

I want to get the value of RequestType and ReceiptNumber. How can I achieve that? I dont need to use XMLDocument= newXMLDocument. I want to use the best way to parse the above XML and get the value of RequestType and some other parameters.

any help will be appreciated.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,313 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,534 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,056 Reputation points Microsoft Vendor
    2023-05-10T02:49:26.9566667+00:00

    Hi @Anjali Agarwal

    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:

    User's image


    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

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful