groovy xml namespace definition used in attribute value lost after XmlParse/serialize

276 views Asked by At

When using XmlParser, it automatically strips out unused namespace definitions. It doesn't appear to detect a namespace being used in a value.

Example Code: The value for attribute "type" is "xs:string" which requires the namespace definition, but XmlParser strips it out

import groovy.xml.XmlUtil

def xml = '''<?xml version="1.0" encoding="UTF-8"?>
<value xmlns:xs="http://xs" type="xs:string">http://localhost:8001/MyService</value>
'''
def doc = new XmlParser().parseText(xml)

println(xml)
println(XmlUtil.serialize(doc))

Output:

****ORIGINAL****
<?xml version="1.0" encoding="UTF-8"?>
<value xmlns:xs="http://xs" type="xs:string">http://localhost:8001/MyService</value>

****XML PARSED/SERIALIZED*****
<?xml version="1.0" encoding="UTF-8"?>
<value type="xs:string">http://localhost:8001/MyService</value>

Is there any way to tell XmlParser to keep this namespace definition??

1

There are 1 answers

0
shnplr On
    def parser = new XmlParser()
    parser.setFeature("http://xml.org/sax/features/namespaces", false)
    parser.setFeature("http://xml.org/sax/features/namespace-prefixes", true)
    doc = parser.parseText(xml)
    println(XmlUtil.serialize(doc))