簡體   English   中英

XML 元素在 c# 中具有前綴讀取問題

[英]XML Element with prefix read issue in c#

我需要獲取特定的 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

這是dotnet fiddler url

可能是什么問題?

您可以使用 Linq 的FirstOrDefault select元素

var statusElement = responseXdoc.Descendants().FirstOrDefault(x => x.Name.LocalName == "ERROR_CODE");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM