Use Linq to Xml with Xml namespaces

LINQ to XML methods like Descendants and Element take an XName as an argument. There is a conversion from string to XName that is happening automatically for you. You can fix this by adding an XNamespace before the strings in your Descendants and Element calls. Watch out because you have 2 different namespaces at work.


string theXml =
                @"true1";

            //string theXml = @"true1";

    XDocument xmlElements = XDocument.Parse( theXml );
    XNamespace ns = "http://myvalue.com";
    XNamespace nsa = "http://schemas.datacontract.org/2004/07/My.Namespace";
    var elements = from data in xmlElements.Descendants( ns + "Result" )
          select new
                 {
                     TheBool = (bool) data.Element( nsa + "TheBool" ),
                     TheId = (int) data.Element( nsa + "TheId" ),
                 };

    foreach ( var element in elements )
    {
        Console.WriteLine( element.TheBool );
        Console.WriteLine( element.TheId );
    }

Notice the use of ns in Descendants and nsa in Elements

Leave a Comment