Groovy(XmlParser)使用变量更新属性值

时间:2016-02-24 18:56:41

标签: groovy

我正在尝试使用变量名更新XML值但不成功。在soapUI中执行以下代码。不确定这是否重要。

String books = '''
    <response version-api="2.0">
        <value>
            <books>
                <book available="20" id="1">
                    <title>Don Xijote</title>
                    <author id="1">Manuel De Cervantes</author>
                </book>
                <book available="14" id="2">
                    <title>Catcher in the Rye</title>
                   <author id="2">JD Salinger</author>
               </book>
               <book available="13" id="3">
                   <title>Alice in Wonderland</title>
                   <author id="3">Lewis Carroll</author>
               </book>
               <book available="5" id="4">
                   <title>Don Xijote</title>
                   <author id="4">Manuel De Cervantes</author>
               </book>
           </books>
       </value>
    </response>
'''

def response = new XmlParser().parseText(books)

def newavailable= "30"
def bookattribute = "available"

response.value.books.book[0].@bookattribute = newavailable

先谢谢。

1 个答案:

答案 0 :(得分:0)

尝试:

import groovy.xml.*

String books = '''
    <response version-api="2.0">
        <value>
            <books>
                <book available="20" id="1">
                    <title>Don Xijote</title>
                    <author id="1">Manuel De Cervantes</author>
                </book>
                <book available="14" id="2">
                    <title>Catcher in the Rye</title>
                   <author id="2">JD Salinger</author>
               </book>
               <book available="13" id="3">
                   <title>Alice in Wonderland</title>
                   <author id="3">Lewis Carroll</author>
               </book>
               <book available="5" id="4">
                   <title>Don Xijote</title>
                   <author id="4">Manuel De Cervantes</author>
               </book>
           </books>
       </value>
    </response>
'''

def response = new XmlParser().parseText(books)

def newavailable= "30";
def bookattribute = "available";

response.value.books.book[0].@"$bookattribute" = newavailable

XmlUtil.serialize(response)