从具有相同名称的节点获取值

时间:2013-05-09 20:03:42

标签: c# .net xml-parsing xmlnode

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

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

我想获得第二个值,这将是库克和人们烹饪食物的描述,但我只得到空节点。例如......

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

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

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

而不是SelectSingleNode,您应该使用SelectNodes:它将返回XmlNodeList nodeList。然后,您应该使用索引[1];

从该节点列表中获取元素的InnerText
public string CareerDescription(string CareerFile)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(CareerFile);
string Description = xmlDoc.SelectNodes("Careers/CareerList/CareerDescription")[1].InnerText;
return Description;
}

有关详细信息,请参阅MSDN上有关此方法的文档:http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.selectnodes%28v=vs.71%29.aspx

答案 2 :(得分:0)

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

return XDocument.Load(CareerFile)
                .Descendants("CareerDescription").Skip(1).First().Value;
相关问题