C# 无法使用Xdocument和Linq分析xml字符串
我想使用Linq中的XDocument解析下面的xmlC# 无法使用Xdocument和Linq分析xml字符串,c#,linq,linq-to-xml,C#,Linq,Linq To Xml,我想使用Linq中的XDocument解析下面的xml <?xml version="1.0" encoding="UTF-8"?> <string xmlns="http://tempuri.org/"> <Sources> <Item> <Id>1</Id> <Name>John</Name> </Item>
<?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>
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();
stringXml=“1John2Max3Ricky”;
XDocument xDoc=XDocument.Parse(stringXml);
var items=xDoc.subjects(“{http://tempuri.org/}来源“?”子代(“{http://tempuri.org/}项目“).ToList();
我测试了它,它正确地显示了items
有3个元素:)也许您使用了不同的名称空间(在对象浏览器中检查xDoc
objct并查看其名称空间就足够了)。尝试下面的代码:
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();
stringXml=“1John2Max3Ricky”;
XDocument xDoc=XDocument.Parse(stringXml);
var items=xDoc.subjects(“{http://tempuri.org/}来源“?”子代(“{http://tempuri.org/}项目“).ToList();
我测试了它,它正确地显示了
items
有3个元素:)也许您使用了不同的名称空间(在对象浏览器中检查xDoc
objct并查看其名称空间就足够了).您需要连接名称空间,并可以直接使用子体
方法获取所有项
节点,如:
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>
1.
约翰
2.
马克斯
3.
瑞奇
请参见您需要连接名称空间,并可以直接使用
子体
方法获取所有项
节点,如:
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>
1.
约翰
2.
马克斯
3.
瑞奇
见