下面是我的XML,通过将serviceListXml打印到控制台获得,如下代码所示:
<?xml version="1.0" encoding="utf-8"?>
<service xml:base="https://fnord/live/api/v1" xmlns="http://www.w3.org/2007/app" xmlns:atom="http://www.w3.org/2005/Atom">
<workspace>
<atom:title type="text">Service List</atom:title>
<collection href="Erp.BO.ABCCodeSvc">
<atom:title type="text">Erp.BO.ABCCodeSvc</atom:title>
</collection>
<collection href="Erp.BO.AccountBudgetSvc">
<atom:title type="text">Erp.BO.AccountBudgetSvc</atom:title>
</collection>
<collection href="Erp.BO.ACTTypeSvc">
<atom:title type="text">Erp.BO.ACTTypeSvc</atom:title>
</collection>
<!-- hundreds more collection elements -->
</workspace>
</service>这是我的密码:
var serviceListXml = client.GetStringAsync(serviceListUrl).GetAwaiter().GetResult();
//serviceListXml = "<foo><bar><collection/><collection/><collection/></bar></foo>";
Console.WriteLine(serviceListXml);
var doc = new XPathDocument(new StringReader(serviceListXml));
var nav = doc.CreateNavigator();
var foo = nav.Select("//collection");
Console.WriteLine("selected " + foo.Count + " elements");这将选择0元素。为什么?
如果我取消注释将serviceListXml设置为测试字符串的行,它会找到3个预期的元素。我认为在我的真实XML上可能有一个BOM,所以我尝试使用serviceListXml.Substring(serviceListXml.IndexOf("<")),但是没有什么区别。
发布于 2018-11-04 21:32:57
这是因为在原始XML集合中位于http://www.w3.org/2007/app名称空间中,这是该XML的默认命名空间。为了能够选择collection元素,您有两个选项:
选项1:将命名空间传递给您的XPathDocument,例如:
var ns = new XmlNamespaceManager(nav.NameTable);
ns.AddNamespace("ns", "http://www.w3.org/2007/app");
var foo = nav.Select("//ns:collection", ns);选项2:使用此XPath:var foo = nav.Select("//*[local-name() = 'collection']");
https://stackoverflow.com/questions/53145491
复制相似问题