如何读取XML数据

时间:2012-08-22 12:02:19

标签: c# xml-parsing

我有XML字符串,我试图用代码

阅读
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(XMLString);
XmlNode node = xmlDoc.SelectSingleNode("//cart/cart-item/url/text()");
Console.WriteLine(node.Value);  

node始终为空。任何人都可以解释什么是错的吗?

<order xmlns="http://ws.plimus.com">
<order-id>8301446</order-id>
<ordering-shopper>
<shopper-id>25879327</shopper-id>
</ordering-shopper>
<cart>
<charged-currency>USD</charged-currency>
<cart-item>
<sku>...</sku>
<quantity>1</quantity>
<url>
https://ws.plimus.com:443/services/2/subscriptions/9433117
</url>
<item-sub-total>9.00</item-sub-total>
</cart-item>
<tax>0.00</tax>
<tax-rate>0</tax-rate>
<total-cart-cost>9.00</total-cart-cost>
</cart>
</order>

2 个答案:

答案 0 :(得分:6)

默认情况下,XPath将未加前缀的名称视为“无命名空间”。您应该使用XmlNamespaceManager来解析xmlns

XmlDocument xmlDoc = new XmlDocument();
XmlNamespaceManager nm = new XmlNamespaceManager(xmlDoc.NameTable);

nm.AddNamespace("ns", "http://ws.plimus.com");
xmlDoc.LoadXml(xmlString);
XmlNode node = xmlDoc.SelectSingleNode("//ns:cart/ns:cart-item/ns:url/text()", nm);

Console.WriteLine(node.Value);  

编辑: 如果您有可能将xml根元素更改为

<order xmlns:ns="http://ws.plimus.com">

然后你不需要每次都在XPath中指定'ns',它看起来像//cart/cart-item/url/text()

无论如何,

XmlNamespaceManager配置如示例所示

答案 1 :(得分:-1)

在xpath中指定//时,它确定从根元素开始,因此您的xpath应为:

XmlNode node = xmlDoc.SelectSingleNode("//order/cart/cart-item/url/text()");