gpt4 book ai didi

C# XmlDocument SelectNodes

转载 作者:数据小太阳 更新时间:2023-10-29 01:43:51 25 4
gpt4 key购买 nike

我有一个带有根元素、两个子元素“诊断”和“结果”的 xml 文档。然后,“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") 没有命中。

最佳答案

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,那绝对值得至少尝试一下。)

关于C# XmlDocument SelectNodes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1247398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com