获取特定类型的所有 XML 元素:甚至是嵌套元素 [英] Grab All XML Elements of a Specific Type: Even nested elements

查看:34
本文介绍了获取特定类型的所有 XML 元素:甚至是嵌套元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 C# ASP.NET 中解析 XML 文档.有没有我不知道的方法/功能来获取标签课程"的所有元素?

I am parsing an XML document in C# ASP.NET. Is there a way/function that I don't know of to get all the elements of the tag "course"?

XML 的格式如下:

<a>
  <g1>
    <course></course>
    <g9>
      <course></course>
      ... more course elements
    </g9>
    <course></course>
    <g2>
      <g3>
        <course></course>
        ...
      </g3>
    </g2>
  </g1>
</a>

当我执行以下代码时,我没有返回课程"元素,是否有一个简单的函数可以一次性获取所有这些元素?

When I do the following code I get back no "course" elements, is there a simple function that can grab all these elements in one go?

XmlDocument xdoc = new XmlDocument();
xdoc.Load("http://kjkjkj.com");
XmlNodeList list = xdoc.DocumentElement.SelectNodes("course");

// if I debug: list.count = 0 but if I look at xdoc.DocumentElement.outerXml 
// its the correct XML so I did parse the file & get XML contents.

// Is there any C# equivalent of document.getElementsByTagName("course"); ???

推荐答案

你已经接近了:

XmlNodeList list = xdoc.DocumentElement.SelectNodes("//course");

// 为前缀将获取所有文档中名为 course 的节点,无论它们位于何处.

Prefixing with // will grab all the nodes in the document named course, no matter where they are.

作为替代方案,您应该考虑使用 Linq to Xml 解析您的 XML,它与 Linq to objects 很好地集成在一起.相同的等效语法是

As an alternative you should consider parsing your XML with Linq to Xml which integrates nicely with Linq to objects. The equivalent syntax for the same there is

var courses  = xdoc.Descendants("course");

这篇关于获取特定类型的所有 XML 元素:甚至是嵌套元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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