从同名节点获取价值 [英] Get value from node with same name

查看:45
本文介绍了从同名节点获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to retrieve information from an XML file, however the way it's formatted is pretty strange. Here it is...

<?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,但是我只得到了一个空节点.例如...

I'd like to get the 2nd value, which would be Cook and the description which is Cooks food for people, but instead I'm getting only the empty node. For example...

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

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

How would I select the second node instead of the first?

推荐答案

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

You can use an index in your XPath expression:

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

请个人注意,我个人将使用LINQ to XML:

Personally I'd use LINQ to XML instead, mind you:

var doc = XDocument.Load(CareerFile);
return doc.Root
          .Elements("CareerList")
          .ElementAt(1) // 0-based
          .Element("CareerDescription")
          .Value;

这篇关于从同名节点获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆