如何解析xml输出并获取机器人框架中特定标记下的元素/子元素的值

时间:2016-07-12 21:43:20

标签: xml robotframework

我尝试解析以下xml输出,并使用robot framework获取标记的元素和子元素。我想获得一个特定的值,例如" adjacency-state"对于2级。由于有多个相同的标签,我该如何实现。

示例:

<isis-adjacency-information>
<isis-adjacency>
    <interface-name>xe-0/0/2:0.0</interface-name>
    <system-name>st-48s-p2-31</system-name>
    <level>1</level>
    <adjacency-state>Up</adjacency-state>
    <holdtime>8</holdtime>
    <snpa>88:e0:f3:1c:a0:7</snpa>
</isis-adjacency>
<isis-adjacency>
    <interface-name>xe-0/0/2:0.0</interface-name>
    <system-name>st-48s-p2-31</system-name>
    <level>2</level>
    <adjacency-state>Up</adjacency-state>
    <holdtime>6</holdtime>
    <snpa>88:e0:f3:1c:a0:7</snpa>
</isis-adjacency>
</isis-adjacency-information>

下面的代码获取第一个xpath匹配的值。但我需要第2级的邻接状态。

${cmd0}=    Execute    Commands Executor    @{target}[0]    command=show isis adjacency    format=xml    xpath=//adjacency-state

欢迎任何建议/想法。 谢谢,

1 个答案:

答案 0 :(得分:1)

Elementtree对谓词的支持有限。因此,您可以迭代元素,寻找合适的元素,而不是使用复杂的XPath。对于测试日志来说,这是一个有点嘈杂的解决方案,但确实有效:

${xml}    Parse Xml    /path/to/example.xml
@{adjacencies}    Get Elements    ${xml}    isis-adjacency
${state}    Set Variable    NOT FOUND
:FOR    ${adjacency}    IN    @{adjacencies}
\    ${level}    Get Element Text    ${adjacency}    level
\    ${state}    Set Variable If    '${level}'=='2'    ${level}    ${state}
\    Exit For Loop If    '${level}'=='2'
Should Not Be Equal    ${state}    NOT FOUND    Did not find state for adjacency of level 2
Log    State is ${state}