3

我想从 XML 文件中检索信息,但是它的格式化方式很奇怪。这里是...

<?xml version="1.0"?>
<Careers>
    <CareerList>
        <CareerName></CareerName>
        <CareerDescription></CareerDescription>
    </CareerList>
    <CareerList>
        <CareerName>Cook</CareerName>
        <CareerDescription>Cooks food for people</CareerDescription>
    </CareerList>
</Careers>

我想获得第二个值,即 Cook 和 Cooks food for people 的描述,但我只得到空节点。例如...

    public string CareerDescription(string CareerFile)
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(CareerFile);
        string Description = xmlDoc.SelectSingleNode("Careers/CareerList/CareerDescription").InnerText;
        return Description;
    }

我将如何选择第二个节点而不是第一个节点?

4

3 回答 3

4

您可以在 XPath 表达式中使用索引:

xmlDoc.SelectSingleNode("Careers/CareerList[2]/CareerDescription").InnerText

我个人会改用 LINQ to XML,请注意:

var doc = XDocument.Load(CareerFile);
return doc.Root
          .Elements("CareerList")
          .ElementAt(1) // 0-based
          .Element("CareerDescription")
          .Value;
于 2013-05-09T20:07:11.920 回答
0

只是 LINQ to XML 例程的直接方式(因为它是 LINQ,我更喜欢这种方式而不是支持 XPath 的 XmlDocument的“标准”用法):

return XDocument.Load(CareerFile)
                .Descendants("CareerDescription").Skip(1).First().Value;
于 2013-05-09T20:53:18.303 回答
0

Instead of SelectSingleNode you should use SelectNodes: it will return XmlNodeList nodeList. Then you should take the InnerText of the element from that node list with index [1];

public string CareerDescription(string CareerFile)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(CareerFile);
string Description = xmlDoc.SelectNodes("Careers/CareerList/CareerDescription")[1].InnerText;
return Description;
}

Refer to the documentation on this method on MSDN for more details: http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.selectnodes%28v=vs.71%29.aspx

于 2013-05-09T20:08:50.323 回答