[英]Getting values from xml file using C#
我是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
是category的屬性而不是子元素。
嘗試: doc.SelectNodes("/Jeopardy/category/@name")
像這樣:
foreach (XmlNode node in nList) {
categories.Add(node.Value);
}
確保文件的編碼與文檔加載方法所需的編碼相匹配。 通常UTF8是XML文件的首選編碼。
如上所述,您可以使用:
doc.SelectNodes("/Jeopardy/category/name");
要么
doc.SelectNodes("//category/name");
要么
doc.SelectNodes("//name");
您需要打開XML文檔
XmlDocument _document = new XmlDocument();
byte[] bytes = File.ReadAllBytes(filePath);
string xml = Encoding.UTF8.GetString(bytes);
try
{
_document.LoadXml(xml);
}
catch (XmlException e)
{
//exception handling
}
var doc = (XmlDocument)_document.CloneNode(true);
XmlNode node = doc.GetElementsByTagName("your child node name");
一旦你得到你的節點,你就可以用它做必要的事情
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.