Pieter VDE
Pieter VDE

Reputation: 2235

Add an attribute to the root tag of a DOM Document/Element

I would like to be able to add a namespace declaration attribute to the root tag of a DOM Document/Element.

Codewise, I'd like to go from something like this:

<xsl:stylesheet 
    xmlns:xlink="http://www.w3.org/TR/xlink/"
    xmlns="http://www.w3.org/1999/xhtml">

To this:

<xsl:stylesheet 
    xmlns:xlink="http://www.w3.org/TR/xlink/"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:util="http://www.url.to.util"> <-- New namespace declaration

What I'm currently trying to do:

xsl.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:util", "http://www.url.to.util")

But clearly, that isn't working. How can I do this, though?

Thanks in advance for your help!

Upvotes: 1

Views: 418

Answers (1)

Ken Shih
Ken Shih

Reputation: 733

Without knowing the constraints of the context you're working in. Here is one way of handling it using DOMBuilder:

import groovy.xml.DOMBuilder
import groovy.xml.XmlUtil

def xmlxsl = '''
<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xlink="http://www.w3.org/TR/xlink/"
    xmlns="http://www.w3.org/1999/xhtml" />
'''
def doc = DOMBuilder.parse(new StringReader(xmlxsl))
def ele = doc.getDocumentElement()
ele.setAttribute("xmlns:util","http://www.url.to.util")

assert XmlUtil.serialize(ele).trim() == 
        '<?xml version="1.0" encoding="UTF-8"?>' +
        '<xsl:stylesheet xmlns="http://www.w3.org/1999/xhtml"' +
        ' xmlns:util="http://www.url.to.util"' +
        ' xmlns:xlink="http://www.w3.org/TR/xlink/"' +
        ' xmlns:xsl="http://www.w3.org/1999/XSL/Transform"/>'

Notice that in the assert string, that the result of ele contains the desired xmlns:util="http://www.url.to.util". On your system, I'm not sure if the order of namespaces will the the same. However, it should be added.

One detail I've added to your original example namespaces was xmlns:xsl="http://www.w3.org/1999/XSL/Transform", so that the xsl namespace itself validates.

Another approach to dealing with editing namespaces can be found on this post (also on Stack Overflow): Use of Namespaces in Groovy MarkupBuilder

Upvotes: 1

Related Questions