C# 读取XML不会返回任何结果
我需要读取以下xml的值:C# 读取XML不会返回任何结果,c#,xml,linq-to-xml,C#,Xml,Linq To Xml,我需要读取以下xml的值: <po-response xmlns="http://test.com<" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="rest/oms/export/v3/purchase-order.xsd"> <!--Generated on Sellpo host [spapp402p.prod.ch4.s.com]--> <pu
<po-response xmlns="http://test.com<" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="rest/oms/export/v3/purchase-order.xsd">
<!--Generated on Sellpo host [spapp402p.prod.ch4.s.com]-->
<purchase-order>
<customer-order-confirmation-number>123456</customer-order-confirmation-number>
<customer-email>test@test.com</customer-email>
<po-number>00001</po-number>
<po-date>2012-02-12</po-date>
<po-time>06:58:40</po-time>
<po-number-with-date>12100000000</po-number-with-date>
<unit>123</unit>
<site>Test</site>
<channel>VD</channel>
<location-id>1234</location-id>
<expected-ship-date>2012-02-13</expected-ship-date>
<shipping-detail>
<ship-to-name>JON DOE</ship-to-name>
<address>123 SOMETHING STREET</address>
<city>NEW NEW</city>
<state>PS</state>
<zipcode>BG121</zipcode>
<phone>012030401</phone>
<shipping-method>Ground</shipping-method>
</shipping-detail>
</purchase-order>
</po-response>
当前您的XML无效-假设您的命名空间声明如下所示
xmlns=”http://test.com“
,您可以使用名称空间获取节点:
xmlDoc = XDocument.Parse(sr.ReadToEnd());
XNamespace ns = "http://test.com";
var details = from detail in xmlDoc.Descendants(ns + "shipping-detail")
select new
{
Name = detail.Element(ns + "ship-to-name").Value,
Address = detail.Element(ns + "address").Value,
City = detail.Element(ns + "city").Value,
};
还要记住,节点名称区分大小写,因此它是“address”
,而不是“address”
您的查询片段:
xmlDoc.Descendants("shipping-detail")
将查看根节点。您没有任何名为“shipping detail”的根节点
试一试
您有一个名称空间,因此您的查询需要使用它。
详细信息
是否为空,或者名称
、地址
和城市
属性是否未填充?@Ed S:那么如何将名称空间包含到查询中?文档将是一个很好的开始。感谢您的帮助,是的,正如你所建议的那样,在名称空间中添加名称空间非常有效……如果答案是错误的,请告诉我原因。我没有考虑使用@BrokenGlass推荐的名称空间。我同意,这将是一个更好的方法。我不是下投票人,但subjects()
将匹配任何后代,无论距离多远,如果使用Elements()
,只返回直接子代,您的示例和解决方案将有意义
xmlDoc.Descendants("shipping-detail")
xmlDoc.Root.Descendants("shipping-detail")