简体   繁体   English

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

[英]Unable to parse xml string using Xdocument and Linq

I would like to parse the below xml using XDocument in 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>

My parsing code is:我的解析代码是:

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

xElements is always null. xElements始终为 null。 I tried using namespace as well, it did not work.我也尝试使用命名空间,它没有工作。 How can I resolve this issue?我该如何解决这个问题?

Try below code:试试下面的代码:

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();

I tested it and it correctly shows that items has 3 lements:) Maybe you used namespaces differently (it's enough to inspect xDoc objct in object browser and see its namespace).我对其进行了测试,它正确地显示了items有 3 个元素:) 也许您使用了不同的命名空间(在 object 浏览器中检查xDoc对象并查看其命名空间就足够了)。

You need to concatenate the namespace and can directly use Descendants method to fetch all Item nodes like:您需要连接命名空间,并且可以直接使用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);
 }

This prints on Console:这在控制台上打印:

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

See the working DEMO Fiddle查看工作中的 DEMO Fiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM