2014-10-17 72 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, 

       });