c# – LINQ to XML:应用XPath

前端之家收集整理的这篇文章主要介绍了c# – LINQ to XML:应用XPath前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有人可以告诉我为什么这个程序不列举任何项目?它与RDF命名空间有关吗?
  1. using System;
  2. using System.Xml.Linq;
  3. using System.Xml.XPath;
  4.  
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. var doc = XDocument.Load("http://seattle.craigslist.org/sof/index.RSS");
  10.  
  11. foreach (var item in doc.XPathSelectElements("//item"))
  12. {
  13. Console.WriteLine(item.Element("link").Value);
  14. }
  15.  
  16. Console.Read();
  17. }
  18. }

解决方法

是的,它绝对是命名空间 – 尽管它是RSS命名空间,而不是RDF.你试图找到没有命名空间的项目.

在.NET中使用XPath中的命名空间有点棘手,但在这种情况下,我只是使用LINQ to XML Descendants方法

  1. using System;
  2. using System.Linq;
  3. using System.Xml.Linq;
  4.  
  5. class Test
  6. {
  7. static void Main()
  8. {
  9. var doc = XDocument.Load("http://seattle.craigslist.org/sof/index.RSS");
  10. XNamespace RSS = "http://purl.org/RSS/1.0/";
  11.  
  12. foreach (var item in doc.Descendants(RSS + "item"))
  13. {
  14. Console.WriteLine(item.Element(RSS + "link").Value);
  15. }
  16.  
  17. Console.Read();
  18. }
  19. }

猜你在找的C#相关文章