【问题标题】:Accessing child nodes of xml by name in Groovy while accessing parent node iteratively迭代访问父节点时在Groovy中按名称访问xml的子节点
【发布时间】:2012-07-09 14:09:15
【问题描述】:

我有一个这样的 XML:

<Envelope>
 <Node>
    <Status>1</Status>
    <Name1>John</Name1>
    <Name2>Smith</Name2>
 </Node>
 <Node>
    <Status>2</Status>
    <Name1>Jane</Name1>
    <Name2>Doe</Name2>
 </Node>
</Envelope>

我想遍历每个节点,如果 Status 的值为 1,则使用 Name1,如果为 2,则使用 Name2。

Envelope = holder.getNodeValues("//ns2:NonProvisionedServers")
for(node in Envelope)
if(node.Status == 1)
{
    assert node.Name1 == "SomeFirstName"
}
if(node.Status == 2)
{
    assert node.Name2 == "SomeLastName"
}

我以前做过最少的 Groovy 脚本。我看过相关的帖子,但它们只遍历子节点,我不想这样做,因为我的父节点有很多子节点,而且我有很多父节点要经过。任何帮助,将不胜感激。

【问题讨论】:

    标签: xml groovy soapui


    【解决方案1】:

    你可以这样做:

    def inx = '''<Envelope>
                |  <Node>
                |    <Status>1</Status>
                |    <Name1>John</Name1>
                |    <Name2>Smith</Name2>
                |  </Node>
                |  <Node>
                |    <Status>2</Status>
                |    <Name1>Jane</Name1>
                |    <Name2>Doe</Name2>
                |  </Node>
                |</Envelope>'''.stripMargin()
    
    // Parse the XML
    def xml = new XmlSlurper().parseText( inx )
    
    // For every <Node> element in the XML
    xml.Node.each { node ->
    
      // Print the child of the node called "Name" + Status
      println node."Name${node.Status}"
    }
    

    打印出来的:

    John
    Doe
    

    【讨论】:

      猜你喜欢
      • 2014-02-19
      • 1970-01-01
      • 2011-01-11
      • 2016-02-02
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多