Reputation: 841
I have an XSD whose root element contains two namespace declarations that aren't used in the subsequent schema definition, e.g., xmlns:foo="urn:bar"
where foo isn't used.
When I use XmlSlurper and StreamingMarkupBuilder to read and write it out again unmodified:
import groovy.xml.MarkupBuilder
import groovy.xml.StreamingMarkupBuilder
public class NS {
public static main(String[] args) {
File xsdFile = new File("A.xsd")
XmlSlurper slurper = new XmlSlurper()
def xml = slurper.parse(xsdFile)
def outputBuilder = new StreamingMarkupBuilder()
String xmlStr = outputBuilder.bind { mkp.yield xml }
println xmlStr
}
}
It is stripping off these namespace declarations. How can I get these to read and write out the XML exactly as-is without any modification?
Upvotes: 0
Views: 2091
Reputation: 171084
Making XmlSlurper
not namespace aware via the constructor seems to give you the result you need:
import groovy.xml.MarkupBuilder
import groovy.xml.StreamingMarkupBuilder
import groovy.xml.XmlUtil
def xsd = '''<?xml version="1.0" encoding="UTF-8"?>
|<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
| xmlns:foo="http://www.example.com/foo">
| <xsd:simpleType name="Severity">
| <xsd:restriction base="xsd:string">
| <xsd:enumeration value="pass"/>
| <xsd:enumeration value="fail"/>
| <xsd:enumeration value="error"/>
| </xsd:restriction>
| </xsd:simpleType>
|</xsd:schema>'''.stripMargin()
def xml = new XmlSlurper( false, false ).parseText( xsd )
def outputBuilder = new StreamingMarkupBuilder()
String xmlStr = XmlUtil.serialize( outputBuilder.bind { mkp.yield xml } )
println xmlStr
Upvotes: 1