Search code examples
c#xmllinq-to-xml

How to read xml-file using XDocument?


I have the xml-file:

<?xml version="1.0" encoding="UTF-8"?>
    <root lev="0">
        content of root
        <child1 lev="1" xmlns="root">
            content of child1
        </child1>
    </root>

and next code:

        XDocument xml = XDocument.Load("D:\\test.xml");

        foreach (var node in xml.Descendants())
        {
            if (node is XElement)
            {
                MessageBox.Show(node.Value);
                //some code...
            }
        }

I get messages:

content of rootcontent of child1

content of child1

But I need to the messages:

content of root

content of child1

How to fix it?


Solution

  • I got needed result by the code:

    XDocument xml = XDocument.Load("D:\\test.xml");
    
    foreach (var node in xml.DescendantNodes())
    {
        if (node is XText)
        {
            MessageBox.Show(((XText)node).Value);
            //some code...
        }
        if (node is XElement)
        {
            //some code for XElement...
        }
    }
    

    Thank for attention!