LINQ XML query does not return data

I experimented with LINQ to XML today, but I was not very successful. When I use the namespace, I get no data.

Here's the (simplified) xml:

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

I am trying to get data using (xmlmsg - 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 the datalist remains empty. If I do not use a namespace, it works.

I used to use XmlReader, which worked great with namespaces. But since my xml data is a bit complicated for parsing, I wanted to use LINQ.

Any clues?

+3
source share
1 answer
        XNamespace ns = root.Name.Namespace;

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

or why it didn’t work; You do not access the attribute value this works too:

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

or

XNamespace ns = root.Attribute("xmlns").Value;
+1

Source: https://habr.com/ru/post/1780632/


All Articles