[英]Get value from xml element in c#
I am trying to get Absoluteentry tag's value from the below xml string, but its displaying objectrefrence not set exception我试图从下面的 xml 字符串中获取 Absoluteentry 标记的值,但其显示 objectrefrence 未设置异常
<?xml version="1.0" ?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
<env:Body>
<AddResponse xmlns="http://www.sap.com/SBO/DIS">
<PickListParams>
<Absoluteentry>120072</Absoluteentry>
</PickListParams>
</AddResponse>
</env:Body>
</env:Envelope>
Code代码
XDocument doc = XDocument.Parse(xmlstring);
doc.Element("Envelope").Element("Body").Element("AddResponse").Element("PickListParams").Element("Absoluteentry").Value;
Look at the XML:查看 XML:
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
...
That's the Envelope
element in the namespace with URI "http://www.w3.org/2003/05/soap-envelope"
.这是名称空间中带有 URI
"http://www.w3.org/2003/05/soap-envelope"
的Envelope
元素。
Now look at your code:现在看看你的代码:
doc.Element("Envelope")...
That's looking for an Envelope
element that's not in any namespace.那就是寻找一个不在任何命名空间中的
Envelope
元素。 You should specify the namespace - and the namespaces of the other elements you're looking for:您应该指定命名空间 - 以及您正在寻找的其他元素的命名空间:
XNamespace env = "http://www.w3.org/2003/05/soap-envelope";
XNamespace responseNs = "http://www.sap.com/SBO/DIS";
XDocument doc = XDocument.Parse(xmlstring);
var result = doc.Element(env + "Envelope")
.Element(env + "Body")
.Element(responseNs + "AddResponse")
.Element(responseNs + "PickListParams")
.Element(responseNs + "Absoluteentry").Value;
You can use Descendants
too.您也可以使用
Descendants
。 Descendants
finds children at any level. Descendants
可以找到任何级别的孩子。
var result = doc.Element(env + "Envelope")
.Element(env + "Body")
.Descendants(responseNs + "Absoluteentry").Value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.