我有一个xml文档,它有一个根元素,两个子元素,'diagnostic‘和'results’。然后,“result”元素具有任意数量的名称为“result”的元素。
当它被加载到XmlDocument中时,很容易导航结构,并看到这正是事情是如何操作的。我可以编写一个递归函数来挑选出所有的"result“元素。结果(“//XmlDocument.SelectNodes”)发现一个节点没有问题。
但是,* 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")不会产生命中结果。
发布于 2009-08-07 23:17:35
Rob和Marc的答案可能是正确的-- XmlDocument + namespaces + XPath可能有点麻烦。
如果你能使用XML3.5,我建议你改用LINQ to .NET。这将使它变得非常简单:
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,它至少值得一试。)
发布于 2009-08-07 23:13:09
在我看来,名称空间才是问题所在;为此,您通常需要获得XmlNamespaceManager的帮助,并在查询中使用别名,例如
doc.SelectNodes("//x:results/x:result", nsmgr);(其中x在nsmgr中定义为给定名称空间的别名)
https://stackoverflow.com/questions/1247398
复制相似问题