开发者

Parse XML Elements with LINQ

开发者 https://www.devze.com 2023-03-22 04:57 出处:网络
I have this xml. <?xml version=\"1.0\" encoding=\"utf-8\"?> <feed xml:lang=\"el-gr\" xmlns=\"http://www.w3.org/2005/Atom\">

I have this xml.

<?xml version="1.0" encoding="utf-8"?>
<feed xml:lang="el-gr" xmlns="http://www.w3.org/2005/Atom">
<title type="text">name.gr</title>
<updated>2011-07-23</updated>
<link href="link" />
<entry>    
  <title type="html">Οι επιθέσεις σε σκανδιναβικές χώρες</title>
  <summary type="text">Η Νορβηγία, μία από τις σκανδιναβικές χώρες, έζησε μετά από πάρα  πολλά χρόνια (2006) τον τρόμο. Δείτε αναλυτικά τις τελευταίες «τυφλές» επιθέσεις τα τελευταία χρόνια:...</summary>
  <published>2011-07-23T12:54:00+03:00</published>    
  <link href="link" />
</entry>

i want to parse some of the elements inside . For that i use the following LINQ code.

var list = from y in xelement.Descendants("entry")
           select new Update()
           {
               Title = y.Element("title").Value,
               Pubdate = y.Element("published").Value,
               Descr = y.Element("content").Value,
               L开发者_如何学运维ink = y.Element("link").Attribute("href").Value
           };

But it does not work. Can anyone tell me what am i doing wrong?


The nodes are all in the http://www.w3.org/2005/Atom namespace. Therefore you need to prefix the queries with this namespace, otherwise the query tries to find those elements in the empty namespace.

XNamespace atom = "http://www.w3.org/2005/Atom";
var list = from y in xelement.Descendants(atom+"entry")
               select new Update()
               {
                   Title = y.Element(atom+"title").Value,
                   Pubdate = y.Element(atom+"published").Value,
                   Descr = y.Element(atom+"content").Value,
                   Link = y.Element(atom+"link").Attribute("href").Value
               };


In your XML example, there is missing "feed" endtag and you are using an element "content", but I guess "summary" is correct.

0

精彩评论

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