【问题标题】:It seems I can't write the right xPath to get the results I need看来我无法编写正确的 xPath 来获得所需的结果
【发布时间】:2019-12-11 01:36:45
【问题描述】:

我正在尝试编写一个 Xpath 来从 XML 文件中检索部分数据,但只获得一级文本值,而不是我需要的整个节点树。

我正在使用来自该地址的动态 XML 文件 -

https://ims.data.gov.il/sites/default/files/IMS_001.xml

包含 10 个地点的天气预报。

部分数据示例如下所示:

<HourlyLocationsForecast>
<Identification>
<Organization>Israel Meteorological Service</Organization>
<Title>Hourly forecasts for selected locations</Title>
<IssueDateTime>Tue Dec 10 06:30:40 IST 2019</IssueDateTime>
</Identification>
<Location>...</Location>
<Location>...</Location>
<Location>...</Location>
<Location>...</Location>
<Location>...</Location>
<Location>...</Location>
<Location>...</Location>
<Location>
<LocationMetaData>
<LocationName>JERUSALEM CENTRE</LocationName>
<LocationLatitude>31.781</LocationLatitude>
<LocationLongitude>35.222</LocationLongitude>
<LocationHeight>810</LocationHeight>
</LocationMetaData>
<LocationData>
<Forecast>
<ForecastTime>10/12/2019 04:00 UTC</ForecastTime>
<Temperature>10.8</Temperature>
<RelativeHumidity>92</RelativeHumidity>
<WindSpeed>2.2</WindSpeed>
<WindDirection>223</WindDirection>
</Forecast>
<Forecast>
<ForecastTime>10/12/2019 05:00 UTC</ForecastTime>
<Temperature>11.0</Temperature>
<RelativeHumidity>91</RelativeHumidity>
<WindSpeed>2.2</WindSpeed>
<WindDirection>226</WindDirection>
</Forecast>
<Forecast>
<ForecastTime>10/12/2019 06:00 UTC</ForecastTime>
<Temperature>11.1</Temperature>
<RelativeHumidity>90</RelativeHumidity>
<WindSpeed>2.2</WindSpeed>
<WindDirection>229</WindDirection>
</Forecast>
</LocationData>
</Location>
<Location>...</Location>
</HourlyLocationsForecast>

我想提取 1 个位置的数据,即序列中的第 8 个。 所以,我试着写了这个 Xpath:

/HourlyLocationsForecast/Location[8]/*

我正在尝试获取该位置的所有数据。相反,我得到的只是位置参数,没有低于其水平的预测。

我做错了什么?

【问题讨论】:

  • 您尚未展示如何应用 XPath 或如何使用结果,仍然难以回答或诊断您的问题。但是,请尝试仅选择带有 XPath /HourlyLocationsForecast/Location[8]Location 元素并将其分配给一个变量,然后您可以进一步询问该元素以获取 LocationMetadataLocationData/Forecast 信息。
  • @MadsHansen 非常感谢! Youre right I didnt 提到了我m implementing this. Im 使用软件工具(Automate BPA Server)的方式,而我m just interested in the proper way to write the XPath. The difference you told me (omitting that last /`所以不需要为*)做了很大的不同,所以现在我要去操纵我拥有的信息量更大的价值。

标签: xml xpath


【解决方案1】:

我不确定你到底在寻找什么,但这个表达式

(/HourlyLocationsForecast/Location/LocationData/Forecast)[8]/descendant::*/text()

输出这个:

2019 年 8 月 7 日 06:00 UTC

28.0

67

2.1

227

这是你的预定目标吗?

【讨论】:

  • 恐怕不是这样。您示例中的 [8] 似乎是指预测 8,我需要位置 8。
  • @Offer - 那么你想要的输出到底是什么?
【解决方案2】:

这是获取第 8 个位置下所有节点的正确 xpath

/HourlyLocationsForecast/Location[8]/descendant::*

截图:

================================================ ======

如果你想要每个节点的文本,那么你可以使用下面的。

/HourlyLocationsForecast/Location[8]/descendant::*/text()

截图:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    相关资源
    最近更新 更多