获得在C#中的XML元素值 [英] Get value from xml element in c#

查看:111
本文介绍了获得在C#中的XML元素值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从下面的XML字符串得到Absoluteentry标签的价值,但其显示objectrefrence没有设置例外

 < ?XML版本=1.0>?; 
< ENV:信封的xmlns:ENV =htt​​p://www.w3.org/2003/05/soap-envelope>
< ENV:身体与GT;
< AddResponse的xmlns =htt​​p://www.sap.com/SBO/DIS>
< PickListParams>
< Absoluteentry> 120072< / Absoluteentry>
< / PickListParams>
< / AddResponse>
< / ENV:身体与GT;
< / ENV:信封>



代码



 的XDocument DOC = XDocument.Parse(的xmlString); 
doc.Element(信封)元素(正文)元素(AddResponse)元素(PickListParams)元素(Absoluteentry)值。。。


解决方案

看XML:

 < ENV:信封的xmlns:ENV =htt​​p://www.w3.org/2003/05/soap-envelope> 
...



这就是信封与URI http://www.w3.org/2003/05/soap-envelope


$的命名空间元素b $ b

现在看看你的代码:

  doc.Element(信封)... 

这是在寻找这不是在信封元素>任何的命名空间。您应指定命名空间 - 你正在寻找其它元素的命名空间:

 的XNamespace ENV =HTTP:/ /www.w3.org/2003/05/soap-envelope; 
的XNamespace responseNs =htt​​p://www.sap.com/SBO/DIS;
的XDocument DOC = XDocument.Parse(的xmlString);
VAR的结果= doc.Element(ENV +信封)
.Element(ENV +身体)
.Element(responseNs +AddResponse)
.Element( responseNs +PickListParams)
.Element(responseNs +Absoluteentry)值。


I am trying to get Absoluteentry tag's value from the below xml string, but its displaying objectrefrence not set exception

<?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:

<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".

Now look at your code:

doc.Element("Envelope")...

That's looking for an Envelope element that's not in any namespace. 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;

这篇关于获得在C#中的XML元素值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆