解析XML仅返回第一个元素

时间:2020-06-02 06:46:36

标签: xml robotframework robotframework-ide

我是机器人框架XML库的新手。 我尝试解析xml以获取其中的值,但是它只会获取第一个元素。 所以我的XML是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
  <S:Header>
    <firstElement>
        <secondElement>
            <myValue>...</myValue>
            <mySecondValue>...</mySecondValue>
            ...
        </secondElement
    </firstElement>
  </S:Header>
  <S:Body>
  ...
  </S:Body>
</S:Envelope>

我非常简短的机器人框架测试如下:

 ${xml}=    Parse Xml    path/to/xml
 ${first}=    get element    ${xml}    myValue
 Log  ${first}

但是在解析XML时,它会这样记录日志:

INFO : ${xml} = <Element 'Envelope' at 0x00000000042B67C8>

当然,我所有尝试在解析的xml中获取值的尝试都失败了,我得到了:

FAIL : No element matching 'myValue' found.

我做错了什么?

1 个答案:

答案 0 :(得分:1)

问题出在您用来查找元素的xpath上,请看这里:https://robotframework.org/robotframework/latest/libraries/XML.html#Finding%20elements%20with%20xpath

它应该像这样:

    ${x}=    Parse Xml    ${xml}    
    ${el_my_value}=    Get Element    ${x}    .//myValue
    Log  ${el_my_value}
    ${first_text}=    Get Element Text    ${el_my_value} 

注意.//myValue

此外,如果要获取元素文本,则需要使用关键字Get Element Text

整个示例和结果如下:

*** Settings ***
Library    XML
Variables    ../../Resources/xml_test.py

*** Test Cases ***
Test XML Parsing
    ${x}=    Parse Xml    ${xml}    
    ${el_my_value}=    Get Element    ${x}    .//myValue
    Log  ${el_my_value}
    ${first_text}=    Get Element Text    ${el_my_value}    

enter image description here

相关问题