Linq to XML-提取单个元素 [英] Linq to XML - Extract Single Element
问题描述
我有一个XML/Soap文件,如下所示:
I have an XML/Soap file that looks like this:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<SendData xmlns="http://stuff.com/stuff">
<SendDataResult>True</SendDataResult>
</SendData>
</soap:Body>
</soap:Envelope>
我想提取SendDataResult值,但是用下面的代码和我尝试过的各种其他方法很难提取出来.即使元素中有值,它也总是返回null.
I want to extract the SendDataResult value but am having difficulty doing so with the following code and various other methods I've tried. It always returns null even though there's a value in the element.
XElement responseXml = XElement.Load(responseOutputFile);
string data = responseXml.Element("SendDataResult").Value;
要提取SendDataResult元素需要做些什么.
What needs to be done to extract the SendDataResult element.
推荐答案
您可以使用Descendants
,然后使用First
或Single
-当前,您正在询问顶级元素它的正下方有一个SendDataResult
元素,而实际上没有.此外,您没有使用正确的名称空间.这应该解决它:
You can use Descendants
followed by First
or Single
- currently you're asking the top level element whether it's got a SendDataResult
element directly beneath it, which it hasn't. Additionally, you're not using the right namespace. This should fix it:
XNamespace stuff = "http://stuff.com/stuff";
string data = responseXml.Descendants(stuff + "SendDataResult")
.Single()
.Value;
或者,直接导航:
XNamespace stuff = "http://stuff.com/stuff";
XNamespace soap = "http://www.w3.org/2003/05/soap-envelope";
string data = responseXml.Element(soap + "Body")
.Element(stuff + "SendDataResult")
.Value;
这篇关于Linq to XML-提取单个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!