Resolved how to parse generic XML envelope and get all nodes values(inner text) separated (not concatenated)

whiteadi

Member
Joined
Nov 19, 2020
Messages
9
Programming Experience
10+
I want to parse ANY SOAP response XML, usually if I have a string xml with response, strXML, and I would do this:


C#:
XmlDocument doc = new XmlDocument();

doc.LoadXml(strXML);

String str = doc.InnerText;

return str;

I would get the values of all nodes, the text, but concatenated.

I want to parse SOAP responses in a generic way.

For example if I have this response envelope coming:

XML:
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:hy="http://www.herongyang.com/Service/">

<soapenv:Header/>

<soapenv:Body>

<hy:GetExchangeRateResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">

<ratePart xsi:type="xsd:decimal">123.14</ratePart>

</hy:GetExchangeRateResponse>

</soapenv:Body>

</soapenv:Envelope>

The c# code above would return me for this envelope the good value but if there would be an extra child node to hy:GetExchangeRateResponse let say :


<ratePart1 xsi:type="xsd:decimal">123.14</ratePart1>
and
<ratePart2 xsi:type="xsd:decimal">234.14</ratePart2>


then I would get: 123.14234.14 concatenated, I want to have something like 123.14, 234.14 ...

PS: usually the services I worked with were returning one value so yeah although is a simple way was working, but not when there are multiple nodes/text.
 
Solution
I also recommend you move from XmlDocument to XDocument/Linq. This example selects the descendant text nodes into an IEnumerable of strings:
C#:
var doc = XDocument.Parse(xml);
var texts = from node in doc.DescendantNodes().OfType<XText>() select node.Value;
I also recommend you move from XmlDocument to XDocument/Linq. This example selects the descendant text nodes into an IEnumerable of strings:
C#:
var doc = XDocument.Parse(xml);
var texts = from node in doc.DescendantNodes().OfType<XText>() select node.Value;
 
Solution

Latest posts

Back
Top Bottom