Get value from xml element in c#

北城以北 提交于 2019-12-20 05:53:07

问题


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;

回答1:


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;



回答2:


You can use Descendants too. Descendants finds children at any level.

var result = doc.Element(env + "Envelope")
    .Element(env + "Body")
    .Descendants(responseNs + "Absoluteentry").Value;


来源:https://stackoverflow.com/questions/30310962/get-value-from-xml-element-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!