【问题标题】:How to read xml-file using XDocument?如何使用 XDocument 读取 xml 文件?
【发布时间】:2017-02-09 15:11:00
【问题描述】:

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

我收到消息:

child1的rootcontent的内容

child1 的内容

但我需要消息:

根目录

child1 的内容

如何解决?

【问题讨论】:

标签: c# xml linq-to-xml


【解决方案1】:

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

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

感谢关注!

【讨论】:

    【解决方案2】:

    一个元素的字符串值是它里面的所有文本(包括里面的子元素。

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

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

    【讨论】:

    • @SQLprog 您还没有明确说明您实际上要做什么,所以我不确定除此之外还有什么建议。
    【解决方案3】:

    改用foreach(XElement node in xdoc.Nodes())

    【讨论】:

      猜你喜欢
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多