我正在尝试从XML文档中获取一些数据。我无法控制架构。如果由我决定,我会选择另一种模式。我正在使用C#的XPATH库来获取数据。
XML DOC
<Journals>
<name>Title of Journal</name>
<totalvolume>2</totalvolume>
<JournalList>
<Volume no="1">
<Journal>
<issue>01</issue>
<Title>Title 1</Title>
<date>1997-03-10</date>
<link>www.somelink.com</link>
</Journal>
<Journal>
<issue>02</issue>
<Title>Title 3</Title>
<date>1997-03-17</date>
<link>www.somelink.com</link>
</Journal>
</Volume>
<Volume no="2">
<Journal>
<issue>01</issue>
<Title>Title 1</Title>
<date>1999-01-01</date>
<link>www.somelink.com</link>
</Journal>
<Journal>
<issue>01</issue>
<Title>Title 2</Title>
<date>1999-01-08</date>
<link>www.somelink.com</link>
</Journal>
</Volume>
</JournalList>
</Journals>
我正在尝试获取Volume 2节点中的所有数据。这是我到目前为止所尝试的:
C#代码:
protected void loadXML(string url)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(url);
string strQuery = "Volume[@no='2']";
XmlElement nodeList = xmlDoc.DocumentElement;
XmlNodeList JournalList = nodeList.SelectNodes(strQuery);
foreach (XmlElement Journal in JournalList)
{
XmlElement temp = Journal;
}
}
似乎JournalList中没有节点。任何人?提前谢谢/
答案 0 :(得分:1)
您的代码正在“Journals”节点
下直接查找“Volume”节点改变这个:
string strQuery = "Volume[@no='2']";
为此,要在“JournalList”节点下查找“Volume”节点:
string strQuery = "JournalList/Volume[@no='2']";
此外,您的XML中还有一些拼写错误:
</Volume no="2"> -> <Volume no="2"> // no open tag found
</Journal> -> </Journals> // expecting end tag </Journals>
根据您的评论:
我将如何访问每个期刊?例如。我想通过每个“期刊”进行评估并获得期刊的标题?
为此,您可以稍微修改一下代码:
var nodeList = xmlDoc.DocumentElement;
var volume = nodeList.SelectSingleNode(strQuery);
foreach (XmlElement journal in volume.SelectNodes("Journal"))
{
var title = journal.GetElementsByTagName("Title")[0].InnerText;
}
答案 1 :(得分:0)
您也可以使用Linq to XML:
using System.Xml.Linq;
//...
string path="Path of your xml file"
XDocument doc = XDocument.Load(path);
var volume2= doc.Descendants("Volume").FirstOrDefault(e => e.Attribute("no").Value == "2");