How do I add features to XML using groovy?
Ask:
In groovy, I need to add an attribute (attribute) to the root element of the XML. I want to use Xmlslurper. What should I do? Adding elements is very simple.
For:
Run the following code in groovy Console with good results.
Import groovy.xml.streamingmarkupbuilder//the original xmldef input = "<foo><bar></bar></foo > "//Add Attributename=" AttributeValue "to the rootdef root = new Xmlslurper (). ParseText (input) [email protected] = ' att Ributevalue '//Get the modified XML and check that it workeddef Outputbuilder = new Streamingmarkupbuilder () String updated Xml = outputbuilder.bind{Mkp.yield root}assert "<foo attributename= ' AttributeValue ' ><bar></bar> </foo> "= = Updatedxml
Adding an attribute is the same as reading a feature:
Import groovy.xml.StreamingMarkupBuilderdef input = ' <thing> <more> </more></thing> ' def root = new Xmlslurper (). ParseText (input) [email protected] = ' new ' def outputbuilder = new Streamingmarkupbuilder () String R Esult = outputbuilder.bind{Mkp.yield root}println result
will be generated:
<thing stuff= ' new ' ><more></more></thing>
Source: >
How to add features to XML using groovy