Al-Punk
Al-Punk

Reputation: 3659

Get the name of namespace xmlns from xsd file through XmlSlurper/XmlParser

I am trying to fetch the namespace for an xml(xsd) file through Groovy. The Node returned by the XmlParsers, and the GPathResult by XmlSlurper seems to ignore the namespace definitions.

As an example:

 <?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.w3schools.com" xmlns="http://www.w3schools.com"
    elementFormDefault="qualified">

trying to fetch the attributes of the rootNode through

rootNode.attributes()

will retrieve only:

targetNamespace:http://www.w3schools.com
elementFormDefault:qualified

and leave out the xml:ns and xmlns definitions. Same result is contained in the @ attribute of GPathResult.

Seems this has nothing to do with the Node class implementation and relies on the XmlParsers used.

So how should the XmlParser be implemented to include these attributes in the node, and any reason this has been left outside of Groovy?

Upvotes: 0

Views: 444

Answers (1)

dmahapatro
dmahapatro

Reputation: 50245

Use a different variant of XmlSlurper constructor:

def xml = """<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.w3schools.com" xmlns="http://www.w3schools.com"
    elementFormDefault="qualified">
</xs:schema>
"""

assert new XmlSlurper(false, false, false).parseText(xml).attributes() == [
    'xmlns:xs':'http://www.w3.org/2001/XMLSchema', 
    'targetNamespace':'http://www.w3schools.com', 
    'xmlns':'http://www.w3schools.com', 
    'elementFormDefault':'qualified'
]

Upvotes: 1

Related Questions