【问题标题】:Get value from node with same name从同名节点获取值
【发布时间】:2013-05-04 10:10:09
【问题描述】:

我想从一个 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 和为人们烹制食物的描述,但我只得到空节点。比如……

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

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

【问题讨论】:

  • 您是否尝试过将 `string Description = xmlDoc.SelectSingleNode("Careers/CareerList/CareerDescription").InnerText;` 更改为类似 string Description = xmlDoc.SelectSingleNode("/Careers/CareerList/@CareerDescription").value; 的内容,您可能会检查是否不为空然后跳过或返回非空描述值

标签: c# .net xml-parsing xmlnode


【解决方案1】:

您可以在 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;

【讨论】:

    【解决方案2】:

    您应该使用SelectNodes 而不是SelectSingleNode:它将返回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

    【讨论】:

    • 虽然 OP 实际上只想选择一个节点 - 所以他可以在 XPath 表达式中进行索引。正如我在回答中所说,我更喜欢使用 LINQ to XML :)
    • 没关系!我提供了一些更通用的解决方案,以防万一:-)。也为您的解决方案投票+。 Rgds, AB
    【解决方案3】:

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

    return XDocument.Load(CareerFile)
                    .Descendants("CareerDescription").Skip(1).First().Value;
    

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多