Java Mailing List Archive

http://www.gg3721.com/

Home » user.groovy »

[groovy-user] Merge XML: suggestions requested

MichaelM

2008-08-17


Author LoginPost Reply

The script below merges several instances of an xml structure.
The simplified example shows 2 xml datasets which overlap in content.
The result is an xml dataset with the same structure, but with the 3
distinct emp records.

Although the script works, I have a few questions:
1. XmlSlurper does not see the xmlns as attributes, so I had to hack a
workaround.
 Is there a way of accessing the xmlns attribute of a node?
2. Would there be a more direct way of merging XML instead of storing
intermediate
 results as maps, and then converting the maps to XML again? Perhaps by
storing
 the nodes and merging in some other way?

A few other remarks on the code below:
a. I chose XMLSlurper over XmlParser because I couldn't get XmlParser to
work with
 the namespace.
b. I chose MarkupBuilder over StreamingMarkupBuilder because MarkupBuilder
formats
 the output.

// ---------- start of script ----------
import groovy.xml.MarkupBuilder

def mergeData = [
'''<?xml version="1.0" encoding="UTF-8" ?>
<Recset xmlns="http://www.ebay.com" version="1.2" id="Dalton" >
<staff>
  <emp id="e1" Leg="a4" xmlns="http://www.ebay.com/s"/>
  <emp id="e2" Leg="b4" xmlns="http://www.ebay.com/s"/>
</staff>
</Recset>''' ,

'''<?xml version="1.0" encoding="UTF-8" ?>
<Recset xmlns="http://www.ebay.com" version="1.2" id="Dalton" >
<staff>
  <emp id="e3" Leg="c4" xmlns="http://www.ebay.com/s"/>
  <emp id="e2" Leg="a4" xmlns="http://www.ebay.com/s"/>
</staff>
</Recset>''' ]

// Declare a map for each of the segments we want to store
// Anomaly? Namespace is not parsed as an attribute, so we set this one
manually
def recsetAttr = ['xmlns': 'http://www.ebay.com']
def staffAttr = [:]   // key is the id

mergeData.each { xmlStr ->
node = new XmlSlurper().parseText(xmlStr)

recsetAttr += node.attributes()
node.staff.emp.each {
  // Namespace is not parsed as an attribute, so add it manually
  staffAttr[it.attributes().id] = it.attributes() +
['xmlns':"http://www.ebay.com/s"]
}
}

// Input sets have been parsed. Write the output.

def writer = new StringWriter()
def eol = System.properties.'line.separator'
writer << '<?xml version="1.0" encoding="UTF-8"?>' << eol
def xml = new MarkupBuilder(writer)
xml.setDoubleQuotes(true)
xml.Recset(recsetAttr) {
staff() {
  staffAttr.each {key, attrMap ->
   emp(attrMap)
  }
}
}
println writer.toString()
// ---------- end of script ----------

--
Sent from the groovy - user mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

  http://xircles.codehaus.org/manage_email


©2008 gg3721.com - Jax Systems, LLC, U.S.A.