2014-10-17 66 views
0

我試圖從此XML中獲取ResponseCode屬性值。從XDocument獲取Atttribute值

的XML是一個XDocument

<IDMResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" MajorVersion="1" xmlns="http://www.fake.org/namespace/"> 
    <ARTSHeader> 
     <Response ResponseCode="Rejected"> 
      <RequestID>1</RequestID> 
      <BusinessError Severity="Error"> 
       <Code>IdmInvalidUserNamePasswordLoginProvided</Code> 
       <Description>Invalid username or password, if problem persists, please contact Administrator</Description> 
      </BusinessError> 
     </Response> 
    </ARTSHeader> 
</IDMResponse> 
+4

你有沒有嘗試過任何東西 – 2014-10-17 04:58:35

回答

0

在XPath:(沒有錯誤檢查完成)

XmlNamespaceManager nsm = new XmlNamespaceManager(new NameTable()); 
nsm.AddNamespace("def", "http://www.fake.org/namespace/"); 
XDocument doc = XDocument.Parse(xml); 
string code = 
    doc 
    .XPathSelectElement(@"/def:IDMResponse/def:ARTSHeader/def:Response", nsm) 
    .Attribute("ResponseCode") 
    .Value; 
+0

作品一種享受。非常感謝。 – tonev 2014-10-18 04:55:19

0
foreach (XElement el in doc.Root.Elements()) 
{ 
    if(el.Name.ToString() == "ARTSHeader") 
     foreach(XElement ell in el.Elements()) 
     { 
      if(ell.Name.ToString() == "Response") 
       string responseCode = ele.Attribute("ResponseCode").Value; 
     } 
} 

這是否對你的工作?我不知道你的XML的整體結構,所以你可能需要去深入嵌套的XML去響應第一

0

一種可能的方式:

..... 
XNamespace ns = "http://www.fake.org/namespace/"; 
string responseCode = (string)doc.Descendants(ns+"Response") 
           .First() 
           .Attribute("ResponseCode"); 
Console.WriteLine(responseCode); 
0

你可以試試這個一出來,我haven`t測試,所以你可能需要重新安排一些結構

XDocument doc1 = XDocument.Parse(soapResult); 
XNamespace ns1 = "http://www.fake.org/namespace/"; 
var items = doc1.Descendants(ns1 + "ARTSHeader").Descendants(ns1 + "Response").First().Attribute("ResponseCode").Descendants(ns1 + "BusinessError").First().Attribute("Severity") 
       .Select((x) => new 
       { 
        Code = x.Element(ns1 + "Code").Value, 
        Description = x.Element(ns1 + "Description").Value, 

       });