XPath:根据多个子条件选择父节点

时间:2015-07-30 01:05:08

标签: xml xpath

这是一个复杂的XPath问题,我无法弄清楚。

假设我有一个包含许多<event>个节点的XML Feed,如下所示:

<bestlinesports_line_feed>
    <event>
    <event_datetimeGMT>2015-07-29 19:10</event_datetimeGMT>
        <sporttype>Baseball</sporttype>
        <scheduletext>null</scheduletext>
        <league>MLB Baseball</league>
        <participant>
            <participant_name>Washington Nationals</participant_name>
            <rotnum>905</rotnum>
            <visiting_home_draw>Visiting</visiting_home_draw>
            <odds>
                <moneyline>-124</moneyline>
            </odds>
            <pitcher>D. Fister -R</pitcher>
        </participant>
        <participant>
            <participant_name>Miami Marlins</participant_name>
            <rotnum>906</rotnum>
            <visiting_home_draw>Home</visiting_home_draw>
            <odds>
                <moneyline>114</moneyline>
            </odds>
            <pitcher>T. Koehler -R</pitcher>
            </participant>
            <drawrotnum>0</drawrotnum>
            <drawmoneyline>0</drawmoneyline>
            <drawTitle/>
        <period>
            <period_description>Game</period_description>
            <periodcutoff_datetimeGMT>2015-07-29 19:20</periodcutoff_datetimeGMT>
            <period_status>O</period_status>
            <spread>
                <spread_visiting>-1.5</spread_visiting>
                <spread_adjust_visiting>125</spread_adjust_visiting>
                <spread_home>1.5</spread_home>
                <spread_adjust_home>-145</spread_adjust_home>
            </spread>
            <total>
                <total_points>7.5</total_points>
                <over_adjust>-102</over_adjust>
                <under_adjust>-118</under_adjust>
            </total>
        </period>
    </event>

现在,这些华盛顿国民赛事节点中有6个。我想基于4个标准来定位这个具体的目标:

  • <participant_name>包含&#39; Nationals&#39; (这缩小到6) (这需要包含因为它们与我的Rails模型连接 那= =&#39;国民&#39;)
  • <event_datetimeGMT>包含&#39; 2015-07-29&#39; (这缩小到了 5)(因为我的Rails game_date模型也需要包含)
  • <league>是MLB Baseball&#39; (将其缩小到2)
  • <period_description>是游戏&#39; (将其缩小到1)

这将是一个巨大的帮助。 XPath真的很难!

如果你感觉特别亲切,那么我选择父事件节点后我要定位的3个字符串/值是主队下的<moneyline>,第二个参赛者或迈阿密马林鱼队(有两个moneylines),然后<total_points><spread_home>。这个xml有点不稳定,所以它变得更难。

非常感谢你。

1 个答案:

答案 0 :(得分:2)

您可以尝试这种方式(格式化以便于阅读):

//event
[
    participant/participant_name[contains(.,'Nationals')]
]
[
    event_datetimeGMT[contains(.,'2015-07-29')]
]
[
    league='MLB Baseball'
]
[
    period/period_description='Game'
]

每个外部谓词([....])按顺序实现问题中提到的四个标准中的每一个。

以下是用于获取所需3个字符串值的3个XPath表达式,给定目标<event>作为上下文节点:

./participant[visiting_home_draw='Home']/odds/moneyline
./period/total/total_points
./period/spread/spread_home