我有一个带有根元素的xml文档,两个子元素,'diagnostic'和'results'。然后'results'元素具有任意数量的元素,名称为'result'
当将它加载到XmlDocument中时,很容易导航结构并看到这正是操作的方式。我可以编写一个递归函数来挑选出所有“结果”元素。 XmlDocument.SelectNodes(“// results”)找到一个节点没问题。
然而, * XmlDocument.SelectNodes(“// results / result”)什么都没找到 * XmlDocument.SelectNodes(“// result”)什么都没找到。
我和一位同事交谈过,他在XmlDocument.SelectNodes中使用Xpath感到很悲伤。还有其他人遇到过这种问题吗?任何解决方案?
XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:count="10" yahoo:created="2009-08-07T10:19:59Z" yahoo:lang="en-US" yahoo:updated="2009-08-07T10:19:59Z" yahoo:uri="http://query.yahooapis.com/v1/yql?q=select+*+from+search.news+where+query%3D%22Tanzania%22">
<diagnostics>
<publiclyCallable>true</publiclyCallable>
<url execution-time="47"><![CDATA[http://boss.yahooapis.com/ysearch/news/v1/Tanzania?format=xml&start=0&count=10]]></url>
<user-time>49</user-time>
<service-time>47</service-time>
<build-version>2579</build-version>
</diagnostics>
<results>
<result xmlns="http://www.inktomi.com/">
<abstract>Kakungulu Cup winners SC Villa face Tanzania’s Simba SC this afternoon at the National stadium in Dar es salaam. “We had a very tiresome journey. The road was so bad and the road blocks were so many. However, we finally reached but the boys were so tired,” said Kato.</abstract>
<clickurl>http://lrd.yahooapis.com/_ylc=X3oDMTQ4cXAxcnRoBF9TAzIwMjMxNTI3MDIEYXBwaWQDb0pfTWdwbklrWW5CMWhTZnFUZEd5TkouTXNxZlNMQmkEY2xpZW50A2Jvc3MEc2VydmljZQNCT1NTBHNsawN0aXRsZQRzcmNwdmlkA21VVGlta2dlQXUzeEYuM0xGQkQzR1pUU1FIS0dORXA4cUk4QUJJX1U-/SIG=12vhpskdd/**http%3A//www.monitor.co.ug/artman/publish/sports/SC_Villa_face_Simba_in_Tanzania_89289.shtml</clickurl>
<date>2009/08/07</date>
<language>english</language>
<source>The Monitor</source>
<sourceurl>http://www.monitor.co.ug/</sourceurl>
<time>20:22:32</time>
<title>SC Villa face Simba in Tanzania</title>
<url>http://www.monitor.co.ug/artman/publish/sports/SC_Villa_face_Simba_in_Tanzania_89289.shtml</url>
</result>
XPATH
doc.SelectNodes(“// result”)不会产生任何命中。
答案 0 :(得分:18)
Rob和Marc的答案可能正朝着正确的方向发展 - XmlDocument +名称空间+ XPath可能会有点痛苦。
如果您能够使用.NET 3.5,我建议您使用LINQ to XML。这将使真的变得容易:
XDocument doc = XDocument.Load("foo.xml");
XNamespace ns = "bar";
var results = doc.Descendants(ns + "result");
foreach (var result in results)
{
...
}
基本上LINQ to XML在几乎所有方面都是一个优秀的API,根据我的经验:)(我相信它缺少一些功能,但如果你能访问.NET 3.5,那么至少值得尝试。)
答案 1 :(得分:12)
听起来像命名空间是问题;你通常需要为XmlNamespaceManager
寻求帮助,并在你的查询中使用别名,即
doc.SelectNodes("//x:results/x:result", nsmgr);
(其中x
在nsmgr
中定义为给定命名空间的别名)