C# 使用特定的XML结构

C# 使用特定的XML结构,c#,xml,xpath,C#,Xml,Xpath,我试图从XML文档中获取一些数据。我无法控制模式。如果由我决定,我会选择另一种模式。我正在使用C#的XPATH库来获取数据 XML文档 <Journals> <name>Title of Journal</name> <totalvolume>2</totalvolume> <JournalList> <Volume no="1"> <Jour

我试图从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>
日志列表中似乎没有节点。任何人提前感谢/

您的代码正在“日志”节点正下方查找“卷”节点

更改此项:

string strQuery = "Volume[@no='2']";
为此,要在“日志列表”节点下查找“卷”节点,请执行以下操作:

此外,您的XML中还有几个输入错误:

</Volume no="2">  ->  <Volume no="2">   // no open tag found

</Journal>        ->  </Journals>       // expecting end tag </Journals>
您还可以使用:


注意,使用XML文档比使用XmlDocument更容易。对于XmlDocument,您基本上只限于使用XPath查询,而对于XDocument,您可以使用它。@slugster LINQ非常好,但它本身并不更好。XPath可以轻松地处理这种情况(以及许多更复杂的情况)。感谢您的回复,但我有一个问题。我将如何访问每个日志?例如我想通过每个“杂志”进行辐照,得到第2卷中的每个杂志标题?我想使用foreach语句,但似乎我只是我被卷2抓住了。如何获取其中的节点?@Grant我相信您的第二个代码示例包含错误。你不应该迭代
xmlDoc.SelectNodes(“//JournalList/Volume[@no=2]”)而不是
Volume.SelectNodes(“Journal”)
?啊,我明白了。它的实现比它需要的要复杂一点,但它可以工作
xmlDoc.SelectNodes(“//JournalList/Volume[@no=2]/Journal”)
会直接选择想要的节点,节省几行。
doc.substands(“Volume”).FirstOrDefault(e=>e.Attribute(“no”).Value==“2”)
-77个字符
doc.SelectNodes(“//卷[@no=2]”)
-34个字符,更易于阅读。
string strQuery = "JournalList/Volume[@no='2']";
</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;
}
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");