c# - 使用C#从xml文件中获取值

标签 c# xml xmlreader

我是 xml 的新手,我不知道如何从下面的 xml 文件中读取/获取值:

<?xml version="1.0" encoding="utf-8" ?>
<Jeopardy>
  <category name = 'People in Computing'>
<first points = '100' answer = 'Alan Turing'>Known as the questioner of the human   mind, this man is known for helping tell humans and computers apart.</first>
<second points = '200' answer = 'Grace Hopper'>This female pioneer of the COBOL computer programming language was an Admiral in the US Navy.</second>
<third points = '300' answer = 'Tim Berners-Lee'>Called the father of the world wide web, this man is the director of the W3C.</third>
<fourth points = '400' answer = 'Lawrence Lessig'>An American academic and political activist who founded the Creative Commons, this man lobbies for reduced legal restrictions on copyrights and trademarks in the technology sector.</fourth>
<fifth points = '500' answer = 'Ada Lovelace'>This woman, known as the world's first computer programmer was also a Countess.</fifth>
  </category>
</Jeopardy>

抱歉,格式很糟糕,无法正确处理。

首先,我尝试在 XDocument 中加载此文件导致“无法将非空白添加到内容”异常,但如果加载到 XmlDocument 中则不会发生。

我尝试获取名称值的代码:

        string fileName = @"C:\Users\Kara\documents\visual studio 2010\Projects\Final Project\Final Project\Jeopardy.xml";

        XmlDocument doc = new XmlDocument();

        doc.Load(fileName);

        List<string> categories = new List<string>();

        XmlNodeList nList = doc.SelectNodes("/category/name");

        foreach (XmlNode node in nList)
        {
            categories.Add(node.ToString());
        }

遗憾的是,在调试 nList 时,计数为零,我无法弄清楚原因。我已经尝试查看此处已有的大量问题和其他地方的教程,但我感到很沮丧。我究竟如何从名称和其他节点中获取值?有人可以解释一下吗?也许为什么我在使用 XDocument 时会出现非空白区域错误?

最佳答案

doc.SelectNodes("/category/name")

您没有找到任何节点,因为 1) 第一个节点是 Jeopardy,而不是 category 和 2) name 是类别不是子元素。

尝试:doc.SelectNodes("/Jeopardy/category/@name")

像这样:

foreach (XmlNode node in nList) {
  categories.Add(node.Value);
}

关于c# - 使用C#从xml文件中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14207811/

相关文章:

c# - 带有法语字符的 URL 编码

C#异常处理范围

xml - xml文件中的DOCTYPE是什么意思?

c# - 如何创建一个立即完成的 IAsyncResult?

c# - C#中foreach循环的性能优化

JAVA - 使用 FasterXml.Jackson 将 XML 文件解析为 Map

java - 制作@XmlTransient 注释只是为了序列化?

c# - 如何在 C# 中从选定的 XML 节点获取所有属性名称

c# - 如何检查未知的 XML 文件以获取其元素或属性?

php - 使用 XMLReader、DOM、Xpath 获取给定节点的标签名称和值