views:

41

answers:

1

With more than a little help from daviderossi.blogspot.com I have managed to get some code working to replace an xml value with another

def fm_xml = '''<?xml version="1.0" encoding="UTF-8"?>
<MAlong>
<Enquiry.ID>SC11147</Enquiry.ID>
<student.name_middle></student.name_middle>
<student.name_known></student.name_known>
<student.name_previous></student.name_previous>
<student.name_cert>John REnfrew</student.name_cert>
<student.detail_gender>M</student.detail_gender>
<student.sign_name>John Renfrew</student.sign_name>
<student.sign_date>05/01/2010</student.sign_date>
</MAlong>'''

xml = new XmlParser().parseText(fm_xml)
ix = xml.children().findIndexOf{it.name() =='student.name_middle'}
nn = new Node(xml, 'student.name_middle', "NEW")
if (ix != -1 ) {
xml.children()[ix] = nn
nn.parent = xml
}
writer = new StringWriter()
new XmlNodePrinter(new PrintWriter(writer)).print(xml)
result = writer.toString()

This give me the following output BUT I would love it to be with properly formed closing tags otherwise XPath queries on the new data will then fail..

so for example

<student.name_known/>

needs to become

<student.name_known></student.name_known>

Any ideas??

<MAlong>
<Enquiry.ID>
 SC11147
</Enquiry.ID>
<student.name_middle>
 NEW
</student.name_middle>
<student.name_known/>
<student.name_previous/>
<student.name_cert>
 John REnfrew
</student.name_cert>
<student.detail_gender>
 M
</student.detail_gender>
<student.sign_name>
 John Renfrew
</student.sign_name>
<student.sign_date>
 05/01/2010
</student.sign_date>
<student.name_middle>
 NEW
</student.name_middle>
</MAlong>
+1  A: 

<student.name_known/>

Is perfectly well formed, and XPath queries should function perfectly well on this XML structure.

Dunderklumpen
Think I had a copy and paste error, it does indeed work, but was still interested in making it slightly more readable
john renfrew
Generally you don't have this level of control with XML parsing. I didn't see any obvious 'pretty print' options for Groovy, but any solution is probably not worth the effort.
Dunderklumpen