首页 > 解决方案 > .Net Core - Use LINQ to XML to get element by name from SOAP response

问题描述

I have found quite a few instances of this type of question asked but for some reason none of the answers in all of those questions have worked for me.

The SOAP response that I get is this very simple one:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
        <GetDataAsStringResponse xmlns="http://tempuri.org/">
            <GetDataAsStringResult>true</GetDataAsStringResult>
        </GetDataAsStringResponse>
    </s:Body>
</s:Envelope>

And these are all the options that I have tried in order to parse it and get to the "GetDataAsStringResult" element:

var doc = XDocument.Parse(responseString);

XNamespace xmlns = "xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"";
XNamespace nsTempuri = "xmlns=\"http://tempuri.org/\"";
var namespacePrefix = doc.Root.GetNamespaceOfPrefix("s");

var resultElement = doc.Descendants("GetDataAsStringResult"); //yields no results
var resultElement1 = doc.Descendants(nsTempuri + "GetDataAsStringResult"); //yields no results
var resultElement2 = doc.Descendants(xmlns + "GetDataAsStringResult"); //yields no results
var resultElement3 = doc.Descendants(namespacePrefix + "GetDataAsStringResult"); //yields no results


var resultElement4 = doc.Descendants(namespacePrefix + "Body"); //Gets s:Body element with descendants

var resultElement5 = resultElement3.Descendants("GetDataAsStringResponse");  //yields no results
var resultElement6 = resultElement3.Descendants(nsTempuri + "GetDataAsStringResponse");  //yields no results
var resultElement7 = resultElement3.Descendants(namespacePrefix + "GetDataAsStringResponse");  //yields no results

var resultElement8 = resultElement4.Descendants(); //Gets IEnumerable with both GetDataAsStringResponse and GetDataAsStringResult

Based on all this experimentation I could do something like the following:

var doc = XDocument.Parse(responseString);
var namespacePrefix = doc.Root.GetNamespaceOfPrefix("s");

var dataAsStringResult = from data in doc.Descendants(namespacePrefix + "Body")
                           let descendats = data.Descendants()
                           select descendats.TakeLast(1).Single();

That looks like too many steps to get to what I need, especially when according to quite some answers in SO I should be able to do it in a much simpler fashion.

Any insights about why I am unable to get directly to the GetDataAsStringResult by using the "Descendants" method even when adding the namespace would be much appreciated.

Thank you.

标签: c#linq-to-xml

解决方案


经过几个小时的疯狂,结果证明这是一个“你错过了分号”的问题。命名空间对象的声明应不带“xlmns=”部分,如下所示:

XNamespace nsTempuri = "http://tempuri.org/";

通过这样做,以下工作:

doc.Descendants(nsTempuri + "GetDataAsStringResult");

推荐阅读