Search code examples
c#.netxmlxmlreader

How to Read XML node attributes?


Hi all below is my XML file.

<print>      
    <part keyName="logo" fontName="" fontSize="" fontColor="" bold="" italic="" underline="" maxWidth="45" textAlign="center" isBarcode="" isImage="true">
        <logo>testimg.jpg</logo>
    </part>      
    <part keyName="header" fontName="" fontSize="" fontColor="" bold="" italic="" underline="" maxWidth="45" textAlign="center" isBarcode="" isImage="">
        <SpaceSep>0</SpaceSep>
        <LineSep>1</LineSep>
        <text fontSize="20">Tax Invoice</text>
        <LineSep>1</LineSep>
        <text>Test Pvt Ltd</text>
        <LineSep>1</LineSep>
        <address/>
        <area/>
        <city/>
        <state/>
        <pin/>
        <country/>
        <LineSep>1</LineSep>
        <text>Phone: </text>
        <phone></phone>
        <LineSep>1</LineSep>
        <text>GSTIN: </text>
        <gstIn></gstIn>
        <LineSep>1</LineSep>
    </part>
</print>

Above XML file contains parent root as Print, And child nodes as part. I want to read child nodes and it's attributes in C#. If XML file contains unique node names then I can read them. But if all child's contains same node name then how can we read them.


Solution

  • If i'm understanding well your question, you should do something like that:

    //...
    using System.Linq;
    using System.Xml.Linq;
    //...
    
    XDocument doc = XDocument.Load(@"C:\directory\file.xml");
    IEnumerable<XElement> partElements = doc.Root.Elements("part");
    
    foreach (XElement partElement in partElements)
    {
        // read attribute value
        string keyName = partElement.Attribute("keyName")?.Value;
    
        //...
    
        // iterate through childnodes
        foreach (XElement partChildElement in partElement.Elements())
        {
            // check the name
            if (partChildElement.Name == "SpaceSep")
            {
                int value = (int)partChildElement; // casting from element to its [int] content
    
                // do stuff for <SpaceSep> element
            }
            else if (partChildElement.Name == "text")
            {
                string text = (string)partChildElement; // casting from element to its [string] content
    
                // do stuff for <text> element
            }
    
            // and so on for all possible node name
        }
    }