如何使用 XDocument 读取 xml-file?

How to read xml-file using XDocument?

我有 xml-文件:

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

和下一个代码:

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

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

我收到消息:

content of rootcontent of child1

content of child1

但我需要消息:

content of root

content of child1

如何解决?

试试 foreach(XElement node in xdoc.Nodes())

元素的字符串值是其中的所有文本(包括内部子元素。

如果要获取每个 non-empty 文本节点的值:

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...
    }
}

我通过代码得到了需要的结果:

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...
    }
}

感谢关注!