whiteadi
whiteadi

Reputation: 133

How to parse GENERIC XML envelope and get all nodes values(inner text) separated (not concatenated)

I want to parse ANY SOAP response XML, not knowing ahead the structure, usually if I have a string xml with response, strXML, and I would do this:

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:

<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, 123.14, but if there would be an extra child node to hy:GetExchangeRateResponse let say :

123.14 and 234.14

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.

Upvotes: 0

Views: 349

Answers (2)

whiteadi
whiteadi

Reputation: 133

using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
                    
public class Program
{
    public static void Main()
    {
        string xxx = "the xml response with multiple final nodes";
        XDocument doc = XDocument.Parse(xxx);
        List<string> texts = (from node in doc.DescendantNodes().OfType<XText>() select node.Value).ToList();
        string asLongString = string.Join(",", texts);
        Console.WriteLine("Values {0}", asLongString);      
    }
}

this guy gave me the answer first sorry :) https://csharpforums.net/members/johnh.4/

Upvotes: 0

Quercus
Quercus

Reputation: 2065

You can fetch all text nodes from the document and then process each node separately. For example:

var texts = doc.SelectNodes("//text()").Cast<XmlNode>().Select(x => x.Value).ToArray();

will fetch all text node values into texts (array of string).

Upvotes: 1

Related Questions