3

我正在使用一个仅是 XML 的 API,而且自从我对 XML 做过任何事情以来,它已经很久了。

响应如下。

我如何获得<status>. 我试过这样做:

XmlNodeList results = xmlDoc.GetElementsByTagName("ProcessRequestResult");

但是我最终得到了充满 XML 的 InnerText,我无法弄清楚如何正确解析。

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<ProcessRequestResponse>
<ProcessRequestResult>
    <ConsumerAddEntryResponse>
          <Status>Failed</Status>
4

3 回答 3

4

使用XmlDocument加载您的 xml并使用XPath获取所需的节点。(我没有测试这条线,但它看起来像这样)

文件加载过程:

var xmlDocument = new XmlDocument();
xmlDocument.Load("someXmlFile.xml");

节点加载过程:

//Single node would be :
XmlNode xNode = xmlDocument.SelectSingleNode("//ConsumerAddEntryResponse/Status");

//More than 1 node would be :
XmlNodeList xNodes = xmlDocument.SelectNodes("//ConsumerAddEntryResponse/Status");
于 2013-04-25T18:56:15.063 回答
4

使用 Linq To Xml 怎么样?

var xDoc = XDocument.Parse(xml); //OR XDocument.Load(filename)
string status = xDoc.Descendants("Status").First().Value;

编辑

我用来测试的xml

string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
            <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
            <soap:Body>
                <ProcessRequestResponse>
                    <ProcessRequestResult>
                        <ConsumerAddEntryResponse>
                                <Status>Failed</Status>
                        </ConsumerAddEntryResponse>
                    </ProcessRequestResult>
                </ProcessRequestResponse>
            </soap:Body>
            </soap:Envelope>";

编辑 2

 string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
            <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
            <soap:Body>
                <ProcessRequestResponse xmlns=""http://submission.api.domain/"">
                    <ProcessRequestResult>
                        <ConsumerAddEntryResponse>
                                <Status>Failed</Status>
                        </ConsumerAddEntryResponse>
                    </ProcessRequestResult>
                </ProcessRequestResponse>
            </soap:Body>
            </soap:Envelope>";

var xDoc = XDocument.Parse(xml);
XNamespace ns = "http://submission.api.domain/";
string status = xDoc.Descendants(ns + "Status").First().Value;
于 2013-04-25T19:12:40.067 回答
0

此外,可以使用 LINQ2XML

var s = "<ProcessRequestResponse.....";
var doc = XDocument.Parse(s);
string value = doc.Element("ProcessRequestResponse")
.Element("ProcessRequestResult")
.Element("ConsumerAddEntryResponse")
.Element("Status")
.Value;
于 2013-04-25T19:08:11.500 回答