从XML获取元素集合

时间:2013-01-14 20:35:58

标签: xml linq linq-to-xml

我有以下XML:

<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
   <author>
      <name />
   </author>
   <title>Publishing Point Collection</title>
   <updated>2013-01-14T15:58:44.589Z</updated>
   <entry>
      <id>http://example.com:80/test filename.isml/settings</id>
      <title>Test Title</title>
      <updated>2013-01-14T15:47:15Z</updated>
      <link href="http://example.com:80/test filename.isml/settings" rel="related" type="application/atom+xml" title="Settings" />
      <link href="http://example.com:80/test filename.isml/state" rel="related" type="application/atom+xml" title="State" />
      <link href="http://example.com:80/test filename.isml/statistics" rel="related" type="application/atom+xml" title="Statistics" />
   </entry>
</feed>

我正在加载文档:

//xmlContent is the XML shown above.
XDocument publishingDocument = XDocument.Parse(xmlContent);

我正在尝试获取所有链接元素(特别是href属性,但是,现在只是元素)。但是,任何时候我指定一个XName我永远不会得到任何结果。我试过了:

var data = publishingDocument.Elements("entry");
var data = publishingDocument.Elements("link").Attributes("href");
var data = publishingDocument.Root.Elements("entry");

这些都不会返回任何数据。我必须遗漏一些非常简单的东西。

1 个答案:

答案 0 :(得分:2)

尝试

XNamespace ns = "http://www.w3.org/2005/Atom";
var data = publishingDocument.Descendants(ns + "entry");