SQLprog
SQLprog

Reputation: 377

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?

Upvotes: 6

Views: 31415

Answers (3)

SQLprog
SQLprog

Reputation: 377

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!

Upvotes: 7

JLRishe
JLRishe

Reputation: 101778

The string value of an element is all of the text that is within it (including inside child elements.

If you want to get the value of every non-empty text node:

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

foreach (var node in xml.DescendantNodes().OfType<XText>())
{
    var value = node.Value.Trim();

    if (!string.IsNullOrEmpty(value))
    {
        MessageBox.Show(value);
        //some code...
    }
}

Upvotes: 3

Rekesoft
Rekesoft

Reputation: 160

Try foreach(XElement node in xdoc.Nodes()) instead.

Upvotes: 0

Related Questions