问题
I call the methods within several classes this way:
GetResult(XElement item, XNamespace ns) {
item.Element(ns + "title").Value;
}
In order to initialize the feeds and to access the elements as stated above I want to find out the default namespace. Without any namespace declaration it works fine (item.Element("title").Value) and the value of the element is returned.
So how can I find out the correct namespace? The result of the method root.GetDefaultNamespace() is empty somehow...
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" version="2.0">
<channel>...</channel>
</rss>
//edit
Ok, my code so far:
XDocument thisFeed = XDocument.Load(@"http://www.spiegel.de/schlagzeilen/tops/index.rss");
XElement root = thisFeed.Root;
XNamespace ns = root.GetNamespaceOfPrefix("content");
//result:
Console.WriteLine("DefaultNamespace: " + root.GetDefaultNamespace());
//result: http://purl.org/rss/1.0/modules/content/
Console.WriteLine("GetNamespaceOfPrefix('content'): " + ns);
//works
Console.WriteLine("Result: " + root.Element("channel").Element("title").Value);
//Doesn't work
Console.WriteLine("Result: " + root.Element(ns + "channel").Element(ns + "title").Value);
回答1:
Try it like this:
XNamespace ns = doc.Root.GetNamespaceOfPrefix("content");
content
in your sample is prefix. Nice explanation of namespaces and prefixes can be found at this w3schools article
UPDATE:
There is no default namespace defined in that document, there is only namespace for elements with prefix, other elements are retrieved without namespace. I found only element <content:encoded>
to be using prefix, for that element you need to use ns
.
来源:https://stackoverflow.com/questions/14957265/linq-to-xml-get-default-namespace-of-rss