3

I experimented with LINQ to XML today, but I wasn't very successful. When I use a namespace I don't get any data.

Here's the (simplified) xml:

<?xml version="1.0" encoding="UTF-8" ?>
<Message xmlns="urn:protocols:format13">
    <data>
    testdata
    </data>
</Message>

I try to get the data with (xmlmsg is a string):

XElement root = XElement.Parse(xmlmsg);
XNamespace ns = root.Attribute("xmlns").ToString();

List<XElement> datalist =
       (from desc in root.Descendants(ns + "data")
         select desc).ToList<XElement>();

But datalist remains empty. If I don't us a namespace it works.

I used XmlReader before, which worked fine with namespaces. But as my xml data gets a little complex to parse, I wanted to use LINQ.

Any hints?

1 Answer 1

1
        XNamespace ns = root.Name.Namespace;

        List<XElement> datalist =
               (from desc in root.Descendants(ns + "data")
                select desc).ToList<XElement>();

or to why it didn't work; you aren't accessing the value of the attribute; this works too:

XNamespace ns = (string)root.Attribute("xmlns");

or

XNamespace ns = root.Attribute("xmlns").Value;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, root.Name.Namespace did work. XNamespace ns = root.Attribute("xmlns").ToString(); looks pretty similar to XNamespace ns = (string)root.Attribute("xmlns");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.