如何使用XDocument读取XML文件?

6

我有一个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...
            }
        }

我收到以下消息:

根目录内容的内容子项1的内容

子项1的内容

但我需要如下的消息:

根目录的内容

子项1的内容

如何解决?


3个回答

6
我通过以下代码得到了所需的结果:
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...
    }
}

感谢关注!

3

元素的字符串值是指包含在它内部的所有文本(包括子元素内部的文本)。

如果您想获取每个非空文本节点的值:

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

1
@SQLprog 你并没有明确表达你实际想要做什么,所以除此之外我也不知道该建议些什么。 - JLRishe

0
尝试使用foreach(XElement node in xdoc.Nodes())代替。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接