2015-02-05 83 views
0

示例XML:解析XML使用LINQ問題

<Response xmlns="http://tempuri.org/"> 
    <Result xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
    <a:string>18c03787-9222-4c9b-8f39-44c2b39c788e</a:string> 
    <a:string>774d38d2-a350-4711-8674-b69404283448</a:string> 
    </Result> 
</Response> 

當我試圖解析此代碼,我又回到空,即:

XNamespace temp = "http://tempuri.org/"; 
XDocument xdoc = XDocument.Parse(xml); 

所有在下列情況下返回null:

xdoc.Descendants(temp + "Result") 
xdoc.Descendants(); 
xdoc.Element(temp + "Result"); 

我誤解了什麼?

******編輯**********

對不起,浪費大家的時間。 看來我使用的是http://www.tempuri.org而不是http://tempuri.org,並且在我的問題中錯誤地列出了正確的一個。

+3

我不能重現。請注意,Descendants()不會返回null,它可以返回一個空序列。我的猜測是XML實際上並不是你想象的那樣。請展示一個簡短但完整的程序來展示問題。我希望最後一行返回null,但是xdoc.Root.Element(temp +「Result」)不會。 – 2015-02-05 20:02:03

+0

你是對的,'xdoc.Root.Element(temp +「Result」)'返回元素,但是這個元素不包含任何元素。 (還奇怪的是,xdoc.root.Desdcendants(temp +「Result」)返回的是{{System.Xml.Linq.XContainer.GetDescendants} name:null self:false System.Collections.Generic.IEnumerator .Current:null System.Collections.IEnumerator.Current:null'我如何使用LINQ qyuery解析出值?我很困難。 – dkirlin 2015-02-05 20:45:00

+1

不,它真的會*包含在這一點上,如果你要提供一個簡短而完整的程序來展示問題,那麼幫助你會容易得多。 – 2015-02-05 20:48:01

回答

1

這裏是你如何能夠拉出值幾個清晰的步驟:

using System; 
using System.Diagnostics; 
using System.Threading.Tasks; 
using System.Xml.Linq; 

namespace WaitForIt 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string thexml = @"<Response xmlns=""http://tempuri.org/""><Result xmlns:a=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><a:string>18c03787-9222-4c9b-8f39-44c2b39c788e</a:string><a:string>774d38d2-a350-4711-8674-b69404283448</a:string></Result></Response>"; 

     XDocument doc = XDocument.Parse(thexml); 
     XNamespace ns = "http://tempuri.org/"; 

     var result = doc.Descendants(ns + "Result"); 
     var resultStrings = result.Elements(); 

     foreach (var el in resultStrings) 
     { 
      Debug.WriteLine(el.Value); 
     } 

     // output: 
     // 18c03787-9222-4c9b-8f39-44c2b39c788e 
     // 774d38d2-a350-4711-8674-b69404283448 
    }   
    } 
}