阅读SOAP xml的答案

时间:2013-12-02 15:21:03

标签: c# xml soap

我必须从下面的文件中读取SOAP答案

<?xml version="1.0"?>
<Envelopes>
 <env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
  <env:Body>
  <env:Fault>
   <env:Code>
    <env:Value>env:Receiver</env:Value>
    <env:Subcode>
     <env:Value>-1</env:Value>
    </env:Subcode>
   </env:Code>
  <env:Reason>
   <env:Text xml:lang="en">CServiceData::SetPropertyValue failed; '</env:Text>
 </env:Reason>
 <env:Detail>
<Object>4</Object>
<ObjectIndex>1</ObjectIndex>
<Command>AddObject</Command>
<SessionID>B8FE2330-4252-4BB1-A3EE-053F4413A0C0</SessionID>
 </env:Detail>
</env:Fault>
</env:Body>
</env:Envelope>
</Envelopes>

我只需要Text标记CServiceData::SetPropertyValue failed;

的内容

1 个答案:

答案 0 :(得分:0)

您可以使用XPath

public string GetErrorMessage(string xml)
{
    using (StringReader sr = new StringReader(xml))
    {
        var doc = new XPathDocument(sr);
        var nav = doc.CreateNavigator();
        var xmlNs = new XmlNamespaceManager(nav.NameTable);
        xmlNs.AddNamespace("env", @"http://www.w3.org/2003/05/soap-envelope");
        var node = nav.SelectSingleNode("//env:Text", xmlNs);
        return node.Value;
    }
}

或者您可以使用LINQ To XML

public string GetErrorMessage(string xml)
{
    var doc = XDocument.Parse(xml);
    var node = doc.Descendants(XName.Get("Text", @"http://www.w3.org/2003/05/soap-envelope"))
                  .FirstOrDefault();
    return node.Value;
}