开发者

Linq to XML : Problem with colon in the xml tags

Here's the code to retrieve the value in the content tag:

   var returnVerse = from item in xmlTreeVerse.Descendants("rss").Elements("channel").Elements("item")
                              select new VerseModel
                               {
                                   Verse = item.Element("content").Value,
                                   Url = ""
                               };

Here's the XML file:

<?xml version="1.0" ?>
<rss version="2.0"
                    xmlns:dc="http://purl.org/dc/elements/1.1/"
                    xmlns:sy="http://purl.开发者_运维百科org/rss/1.0/modules/syndication/"
                    xmlns:admin="http://webns.net/mvcb/"
                    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
                    xmlns:content="http://purl.org/rss/1.0/modules/content/">

  <channel>
    <title>text</title>
    <link>text</link>
    <item>
      <title>text</title>
      <content:encoded>
        Text
      </content:encoded>
    </item>
  </channel>
</rss>

I can't query "content:encode" because it is invalid to query the ":" operator. Please help.


That "colon operator" is a namespace. You need to query with a namespace as well. You use namespaces like this:

XNamespace content = XNamespace.Get("http://purl.org/rss/1.0/modules/content/");
Verse = item.Element(content + "encoded").Value


This worked for me, so mapped back to content:encoded for this question

var ns = XNamespace.Get(@"http://purl.org/rss/1.0/modules/content/");

var xelems = xmlDoc.Descendants().ToList();

nodes.ForEach(n => n.Element(XName.Get("encoded", ns.NamespaceName)).Value);

var elems = from x in xelems 
  select x.Element(XName.Get("encoded", ns.NamespaceName)).Value

If you want to quickly test this works on a public RSS feed, run this code in a console app or on LinqPad up here on Gist.


Instead of

item.Element("content").Value

Try this:

item.Element(XName.Get("encoded", "content")).Value

If item.Element() returns null there, you may need to use this instead:

item.Element(XName.Get("encoded", "http://purl.org/rss/1.0/modules/content/")).Value
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜