Search code examples
c#xmlparsingresponse

Parse XML response in C#


I got an XML response as:

<?xml version='1.0' encoding='UTF-8'?>
<tsResponse xmlns="site.com/api" xmlns:xsi="site.org/2001/XMLSchema-instance" xsi:schemaLocation="site.com/api help.site.com/samples/en-us/rest_api/ts-api_3_4.xsd">
    <credentials token="xxxxxx-xxxxxx-xxxxxx">
        <site id="xxxxxx-xxxxxx-xxxxxx" contentUrl="sitename"/>
        <user id="xxxxxx-xxxxxx-xxxxxx"/>
    </credentials>
</tsResponse>

How can I parse this response to get the token value inside credentials?


Solution

  • I think that the simplest way is to use LINQ to XML's XDocument:

    using System.Xml;
    using System.Xml.Linq;
    
    /* ... */
    
    var xml = @"<?xml version='1.0' encoding='UTF-8'?>
    <tsResponse xmlns=""site.com/api"" xmlns:xsi=""site.org/2001/XMLSchema-instance"" xsi:schemaLocation=""site.com/api help.site.com/samples/en-us/rest_api/ts-api_3_4.xsd"">
        <credentials token=""xxxxxx-xxxxxx-xxxxxx"">
            <site id=""xxxxxx-xxxxxx-xxxxxx"" contentUrl=""sitename""/>
            <user id=""xxxxxx-xxxxxx-xxxxxx""/>
        </credentials>
    </tsResponse>";
    
    var xmlns = XNamespace.Get("site.com/api");
    var token = XDocument.Parse(xml)
                         .Element(xmlns + "tsResponse")?
                         .Element(xmlns + "credentials")?
                         .Attribute("token")?
                         .Value;