簡體   English   中英

C#XmlDocument SelectNodes

[英]C# XmlDocument SelectNodes

我有一個帶有根元素的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”)不會產生任何命中。

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,那么至少值得嘗試。)

聽起來像命名空間是問題; 您通常需要為此獲得XmlNamespaceManager的幫助,並在查詢中使用別名,即

doc.SelectNodes("//x:results/x:result", nsmgr);

(其中xnsmgr定義為給定命名空間的別名)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM