【问题标题】:Unable to parse xml string using Xdocument and Linq无法使用 Xdocument 和 Linq 解析 xml 字符串
【发布时间】:2020-01-27 10:53:50
【问题描述】:

我想在 Linq 中使用 XDocument 解析下面的 xml。

<?xml version="1.0" encoding="UTF-8"?>
<string xmlns="http://tempuri.org/">
   <Sources>
      <Item>
         <Id>1</Id>
         <Name>John</Name>
      </Item>
      <Item>
         <Id>2</Id>
         <Name>Max</Name>
      </Item>
      <Item>
         <Id>3</Id>
         <Name>Ricky</Name>
      </Item>
   </Sources>
</string>

我的解析代码是:

    var xDoc = XDocument.Parse(xmlString);
    var xElements = xDoc.Element("Sources")?.Elements("Item");
    if (xElements != null)
        foreach (var source in xElements)
        {
            Console.Write(source);
        }

xElements 始终为空。我也尝试使用命名空间,它没有工作。我该如何解决这个问题?

【问题讨论】:

    标签: c# linq linq-to-xml


    【解决方案1】:

    试试下面的代码:

    string stringXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><string xmlns=\"http://tempuri.org/\"><Sources><Item><Id>1</Id><Name>John</Name></Item><Item><Id>2</Id><Name>Max</Name></Item><Item><Id>3</Id><Name>Ricky</Name></Item></Sources></string>";
    XDocument xDoc = XDocument.Parse(stringXml);
    var items = xDoc.Descendants("{http://tempuri.org/}Sources")?.Descendants("{http://tempuri.org/}Item").ToList();
    

    我对其进行了测试,它正确地表明 items 有 3 个元素 :) 也许您使用了不同的命名空间(在对象浏览器中检查 xDoc 对象并查看其命名空间就足够了)。

    【讨论】:

      【解决方案2】:

      需要拼接命名空间,可以直接使用Descendants方法获取所有Item节点,如:

      XNamespace ns ="http://tempuri.org/";
      var xDoc = XDocument.Parse(xmlString);
      var xElements = xDoc.Descendants(ns + "Item");
      
       foreach (var source in xElements)
       {
           Console.Write(source);
       }
      

      这在控制台上打印:

      <Item xmlns="http://tempuri.org/">
        <Id>1</Id>
        <Name>John</Name>
      </Item><Item xmlns="http://tempuri.org/">
        <Id>2</Id>
        <Name>Max</Name>
      </Item><Item xmlns="http://tempuri.org/">
        <Id>3</Id>
        <Name>Ricky</Name>
      </Item>
      

      working DEMO Fiddle

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多