Search code examples
c#xml

c# XMLDocument values to List/Array


I know there are a lot of the same questions but I can't crack this one. I have an XMLDocument and I need to iterate through the values.

        <InfoResponse xmlns="">
           <ns1:ID xmlns:ns1="http://www.svt.si/evlog">2399237000/03-069-1-41/2023</ns1:ID>
           <ns1:ID xmlns:ns1="http://www.svt.si/evlog">2399237000/03-069-1-42/2023</ns1:ID>
        </InfoResponse>

I have tried with IEnumerable, XmlNodelist, List and always get the same result.

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(response);

String test = xmlDocument.InnerText;

returns

2399237000/03-069-1-41/20232399237000/03-069-1-42/2023

I need an array or a list so I can iterate through and perform next action.

I tried the suggested solutions How do I read and parse an XML file in C#? but the result is the same. I think the problem is that they all have the same node name/id.

Edit As suggested the namespace ns1 might not be defined so here is the whole string response I get:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Header xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"/>
    <soap:Body>
        <InfoResponse xmlns="">
            <ns1:ID xmlns:ns1="http://www.svt.si/evlog">2399237000/03-069-1-41/2023</ns1:ID>
            <ns1:ID xmlns:ns1="http://www.svt.si/evlog">2399237000/03-069-1-42/2023</ns1:ID>
        </InfoResponse>
    </soap:Body>
</soap:Envelope>

Is the response ok?

I'm adding the suggested solution with the foreach - at this point I'm not sure, if I'm doing it correctly:

string[] strArray = XElement.Parse(response)
                        .Elements()
                        .Select(d => d.Value)
                        .ToArray();

foreach (string xn in strArray)
{
    Logger.LogInfo("ID: " + xn);
}

This now returns 2 elements - One empty and the other has both values.

Edit2

        string[] strArray = XElement.Parse(soapResponse)
                                    .Descendants("InfoResponse")
                                    .Elements()
                                    .Select(d => d.Value)
                                    .ToArray();

returns an empty array..


Solution

  • it is always easier to use Linq

    string[] test = XElement.Parse(response)
                                .Descendants("InfoResponse")
                                .Elements()
                                .Select(d => d.Value)
                                .ToArray();