XmlDocument - 选择节点

XmlDocument - SelectNodes

我尝试了很多不同的方法,但没有太多的了解,我希望有人能够提供帮助:-)

XML:

<?xml version="1.0" encoding="UTF-8"?>
<ListOrdersResponse xmlns="https://services.com/Orders/2013-09-01">
   <ListOrdersResult>
      <Orders>
         <Order>
            <Id>1</Id>
         </Order>
         <Order>
            <Id>2</Id>
         </Order>
      </Orders>
   </ListOrdersResult>
</ListOrdersResponse>

尝试过:

var o =xmlDocument.SelectNodes("/ListOrdersResponse/ListOrdersResult/Orders/Order");
var o = xmlDocument.SelectNodes("/ListOrdersResponse/ListOrdersResult/Orders");
var o = xmlDocument.SelectNodes("//Orders");
var o = xmlDocument.SelectNodes("//Order");
var o = xmlDocument.SelectNodes("//Orders/Order");

var root = xmlDocument.DocumentElement;
var nsmgr = new XmlNamespaceManager(xmlDocument.NameTable);
nsmgr.AddNamespace("bk", "https://services.com/Orders/2013-09-01");
var orders = root.SelectNodes("descendant::bk:Orders/Order", nsmgr);

var root = xmlDocument.DocumentElement;
var nsmgr = new XmlNamespaceManager(xmlDocument.NameTable);
nsmgr.AddNamespace("bk", "https://services.com/Orders/2013-09-01");
var orders = root.SelectNodes("descendant::bk:Orders", nsmgr);

只有returns 0条记录。 :-(

我做错了什么?

使用 Linq2Xml 怎么样?我发现它更容易使用。

XNamespace ns = "https://services.com/Orders/2013-09-01";
var orders = XDocument.Load(filename)
            .Descendants(ns + "Order")
            .Select(x => (int)x.Element(ns + "Id"))
            .ToList();

PS: Xml区分大小写。检查有问题的样品。 <Order></order> 等等

var nsmgr = new XmlNamespaceManager(xmlDocument.NameTable);
nsmgr.AddNamespace("bk", "https://services.com/Orders/2013-09-01");

部分是正确的,但您需要使用前缀 bk 来限定 XPath 表达式中的所有元素名称,例如

XmlNodeList orders = xmlDocument.SelectNodes("//bk:Orders/bk:Order", nsmgr);
foreach (XmlElement order in orders) {
  Console.WriteLine(order.SelectSingleNode("bk:Id", nsmgr).InnerText);
}