【问题标题】:XPath not working as expectedXPath 未按预期工作
【发布时间】:2011-06-10 05:04:34
【问题描述】:

我有一个这种格式的 XML 文档:

<?xml version="1.0" encoding="utf-8" ?>
<SupportedServices>
  <Service>
    <name>Google Weather</name>
    <active>Yes</active>
  </Service>
   ...
</SupportedServices>

我正在尝试像这样解析 XML 文件:

public void InitializeDropDown(string XmlFile, string xpath)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(XmlFile);

    var rootNode = doc.DocumentElement;

    var serviceList = rootNode.SelectNodes(xpath);

    Parallel.ForEach(serviceList.Cast<XmlNode>(), service =>
    {
        if (Properties.Settings.Default.ServiceActive &&
            Properties.Settings.Default.ServiceName == service.InnerText)
        {
            WeatherServicesCBO.Items.Add(service.InnerText);
        }
    });
}

我遇到的问题是两个值(名称和活动)都被选中,所以它看起来像 Google WeatherYes,而我想要的只是 Google Weather .谁能告诉我我的 XPath 出了什么问题(在这里):

InitializeDropDown("SupportedWeatherServices.xml", "descendant::Service[name]");

【问题讨论】:

    标签: c# .net xml c#-4.0 xpath


    【解决方案1】:

    XPath 应该是//Service/name

    var serviceList = rootNode.SelectNodes("//Service/name");
    

    descendant::Service/name,如果你更喜欢这种语法。

    【讨论】:

    • 感谢您的提示,它很漂亮。 ut 从技术上讲,我原来的 xpath 出了什么问题?
    • Service[name] 选择一个 Service,只要它有一个名字 child。 Service/name 选择名称 child。
    猜你喜欢
    • 1970-01-01
    • 2019-11-06
    • 2012-05-07
    • 2021-06-04
    • 2022-01-24
    • 2015-05-11
    • 2020-05-15
    • 2014-10-31
    • 2018-02-12
    相关资源
    最近更新 更多