Linq and XML string

What do you do when a server returns to you an XML string? How do you parse or query this string? There are 2 main ways that you can solve this problem. Using XDocoument or using XElement.

1. The XDocument way
1.1 To Load the string

private XDocument GetXDocument(string xmlString)
{
    return XDocument.Load(new System.IO.StringReader(xmlString));
}

1.2 To Parse or query the string

XDocument doc = GetXDocument(temp);
IEnumerable<string> textProtocols =
    from mail in doc.Root.Descendants("EMail")
    select (string)mail;

2. The XElement Way
I am going to combine Loading and Parsing into one function for brevity purposes

public static List<string> GetElements(string xmlString, string descendant)
{
    List<string> ret = new List<string>();

    TextReader sr = new StringReader(result);
    XElement xmlTree = XElement.Load(sr);
    sr.Close();

    IEnumerable<XElement> items =
        from el in xmlTree.Descendants(descendant)
        select el;
    foreach (XElement elt in items)
    {
        ret.Add((string)elt);
    }

    return ret;
}

Missing Name Space

Sometimes you may get a XML string with missing namespaces. The easiest way to resolve this is to you string replace.
XML

<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelop"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
    <soap:Body>
        <m:Password>
            Password
        </m:Password>
    </soap:Body>
</soap:Envelope

Code

// Resolve missing Namespace
string result = xmlString.Replace("m:", string.Empty);

Alternative solution to missing namespaces

I have found out the Load method of XDocument allows you to load files with missing namespace. You can save the XML string to a file then load the file

Comments are closed.