使用LINQ解析XML元素 [英] Parse XML Elements with LINQ

查看:79
本文介绍了使用LINQ解析XML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个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>

我想解析其中的某些元素.为此,我使用以下LINQ代码.

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,
               Link = y.Element("link").Attribute("href").Value
           };

但是它不起作用.谁能告诉我我在做什么错?

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

推荐答案

节点全部位于http://www.w3.org/2005/Atom命名空间中.因此,您需要在查询之前为此名称空间添加前缀,否则查询将尝试在空名称空间中查找那些元素.

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
               };

这篇关于使用LINQ解析XML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆