2009-10-28 31 views
20

我想在XDocument對象中使用LINQ to XML。你如何在下面的例子中查詢結果元素?如何在元素名稱中包含冒號的情況下使用LINQ查詢XDocument?

<serv:header> 
    <serv:response> 
     <serv:result>SUCCESS</serv:result> 
     <serv:gsbStatus>PRIMARY</serv:gsbStatus> 
    </serv:response> 
</serv:header> 

當我使用這樣的說法,我得到的異常「的附加信息:‘:’字符,十六進制值0x3A,不能包含在一個名稱。」

XDocument doc = XDocument.Parse(xml); 
string value = doc.Descendants("serv:header").First().Descendants("serv:response").First().Descendants("serv:result").First().Value; 

回答

38

serv在你的XML是一種命名空間前綴。它必須與一些標識名稱空間的URI相關聯。在XML中查找這樣的屬性:

xmlns:serv="..." 

引號內的值將是命名空間。現在,在你的C#代碼,您使用URI來創建一個XNamespace對象:

private static readonly XNamespace serv = "..."; 

然後你就可以使用,在查詢這樣的:

string value = doc 
    .Descendants(serv + "header").First() 
    .Descendants(serv + "response").First() 
    .Descendants(serv + "result").First() 
    .Value; 

順便說一句,你應該考慮使用.Element()而不是.Descendants().First()

+0

我能夠使用'doc.Root.GetNamespaceOfPrefix(「serv」)' – 2017-08-03 14:09:43

6

該冒號表示XML使用的是namespaces。在此基礎上blogpost有人張貼了關於LINQ,XML和命名空間,這裏是你的代碼的版本,您可能會想嘗試:

static XName serv(string name) 
{ 
    return XNamespace.Get("<THE_NAMESPACE_URL>") + name; 
} 

XDocument doc = XDocument.Parse(xml); 
string value = doc.Descendants(serv("header")).First().Descendants(serv("response")).First().Descendants(serv("result")).First().Value; 
相關問題