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;
精彩评论