无法使用 Xdocument 和 Linq 解析 xml 字符串

Unable to parse xml string using Xdocument and Linq

我想在 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 始终为空。我也尝试使用命名空间,但没有用。我该如何解决这个问题?

试试下面的代码:

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 objct 并查看它的名称空间就足够了)。

您需要连接命名空间,可以直接使用 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