我需要获取一个特定的xml元素值。下面是我拥有的xml代码
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:hdr="http://www.example.com/hdr/">
<soapenv:Header>
<hdr:ERROR_CODE>0</hdr:ERROR_CODE>
<hdr:ERROR_DESC>Success</hdr:ERROR_DESC>
<hdr:ASYNCH_RESPONSE_INDICATOR>0</hdr:ASYNCH_RESPONSE_INDICATOR>
</soapenv:Header>
<soapenv:Body><CREATE_RESPONSE></CREATE_RESPONSE>
</soapenv:Body>
</soapenv:Envelope>
下面是我尝试过的方法
var response = @"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:hdr='http://www.example.com/hdr/'>
<soapenv:Header>
<hdr:ERROR_CODE>0</hdr:ERROR_CODE>
<hdr:ERROR_DESC>Success</hdr:ERROR_DESC>
<hdr:ASYNCH_RESPONSE_INDICATOR>0</hdr:ASYNCH_RESPONSE_INDICATOR>
</soapenv:Header>
<soapenv:Body><CREATE_RETAILER_RESPONSE></CREATE_RETAILER_RESPONSE>
</soapenv:Body>
</soapenv:Envelope>";
var responseXdoc = XDocument.Parse(response);
var nsManager = new XmlNamespaceManager(new NameTable());
nsManager.AddNamespace("hdr", "http://www.example.com/hdr");
var statusElement = responseXdoc.XPathSelectElement("//hdr:ERROR_CODE", nsManager);
Console.WriteLine(statusElement.Value);
它返回此错误
[System.NullReferenceException: Object reference not set to an instance of an object.]
at Program.Main() :line 26
问题可能是什么?
发布于 2021-03-23 15:40:32
您可以使用Linq的FirstOrDefault选择元素
var statusElement = responseXdoc.Descendants().FirstOrDefault(x => x.Name.LocalName == "ERROR_CODE");
https://stackoverflow.com/questions/66758493
复制相似问题