问题描述
我对xml很陌生,我不知道如何从下面的xml文件读取/获取值:
I'm pretty new to xml and I don't know how to read/get values from xml file below:
<?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>
很抱歉,格式糟糕,无法正确显示.
Sorry for the terrible formatting, can't get it right.
首先,我试图将此文件加载到XDocument中,导致出现无法将非空白空间添加到内容中"异常,但是如果加载到XmlDocument中则不会发生.
First of all, I tried to load this file in XDocument results in a "Non-white space cannot be added to content" exception, but it didn't occur if loaded into XmlDocument.
我尝试获取名称值的代码:
My code to attempt to get the name value:
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收到非空白错误?
Sadly while debugging the nList has a count of zero and I cannot figure out why. I've tried looking at a ton of questions already on here and tutorials elsewhere and I'm just getting frustrated. How in the world do I get the values out of name and other nodes? Can someone explain this? And perhaps why I get the non-white space error with XDocument?
推荐答案
doc.SelectNodes("/category/name")
您没有找到任何节点,因为1)第一个节点是 Jeopardy
,而不是 category
和2) name
是类别不是子元素.
You're not finding any nodes because 1) the first node is Jeopardy
, not category
and 2) name
is an attribute of category not a child element.
尝试: doc.SelectNodes("/Jeopardy/category/@ name")
赞:
foreach (XmlNode node in nList) {
categories.Add(node.Value);
}
这篇关于使用C#从xml文件获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!