使用特定 XML 结构

Working With Specific XML structure

我正在尝试从 XML 文档中获取一些数据。我无法控制模式。如果由我决定,我会选择另一个模式。我正在使用 C# 的 XPATH 库来获取数据。

XML 文档

<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>

我正在尝试获取第 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 中似乎没有节点。任何人?提前致谢/

您的代码正在寻找 "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>

来自您的下方评论:

how would I go about access each journal? for example. I want irrate through each "journal" and get the title of the journal?

为此,您可以稍微修改一下代码:

var nodeList = xmlDoc.DocumentElement;
var volume = nodeList.SelectSingleNode(strQuery);
foreach (XmlElement journal in volume.SelectNodes("Journal"))
{
    var title = journal.GetElementsByTagName("Title")[0].InnerText;
}

您也可以使用 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");