简体   繁体   中英

XML LINQ query returns no data

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?

        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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM