我正在使用仅限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>
答案 0 :(得分: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");
答案 1 :(得分:3)
如何使用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;
答案 2 :(得分:0)
此外,还可以使用LINQ2XML
var s = "<ProcessRequestResponse.....";
var doc = XDocument.Parse(s);
string value = doc.Element("ProcessRequestResponse")
.Element("ProcessRequestResult")
.Element("ConsumerAddEntryResponse")
.Element("Status")
.Value;