|
This note is for scripting tool Groovy version 1.8 and the java library JDOM, version 1.1.1.
I was trying to remove an attribute from an xml element. The xml element had been parsed using XmlSlurper:
<root>
<record id="remove">Some text</record>
<record>Some other text</record>
</root>
The attribute id can be removed with the Groovy code below.
def xml = ...
def root = new XmlSlurper().parseText(xml)
def record = root.record.find{ it.@id=='remove'}.each { p -> p.attributes().remove('id') }
The call to attributes() returns a java Map from which the attribute can be deleted using the remove(..) method by supplying the key id for the argument.
Don't use XmlSlurper or XmlParser if your XML contains CDATA sections and you need to write it after processing. In most cases the CDATA's will not be written although their contents will be written in escaped form. For example:
<root><test><![CDATA[1<2]]></test><root>
could end up as
<root><test>1<2</test></root>
So if your xml contains CDATA sections it is better to use another java XML parser, such as JDOM. JDOM preserves whitespace and CDATA elements if you use the Format.getRawFormat() format in the constructor argument of XMLOutputter. There is one exception, which is when the CDATA element is empty. In that case JDOM removes the CDATA element. This behavior broke another tool reading the processed xml. As a work around I added a space to each empty CDATA element in my xml files.
|