开发者

How do you set the namespace of a Groovy Node object to another value?

开发者 https://www.devze.com 2023-03-22 15:58 出处:网络
I\'m converting an XML document from one namespace (and schema) to another. JDOM allows us to call Element.setNamespace() (which also takes care of the attributes for the element). The closest I can s

I'm converting an XML document from one namespace (and schema) to another. JDOM allows us to call Element.setNamespace() (which also takes care of the attributes for the element). The closest I can see with a Groovy Node is

myNode.name = new QName("http://开发者_如何学编程my/new/namespace", myNode.name.localPart)

But I'm not confident that this is the best way - in particular, it doesn't take care of the attributes. Is this even possible with Node? And if so, what's the idiomatic way to do it?


I can't think of a way off-hand... You could just use JDOM though (converted to a Groovy script from this example)

@Grab(group='org.jdom', module='jdom', version='1.1')
import org.jdom.*
import org.jdom.input.*
import org.jdom.output.*

new SAXBuilder().build( new URL( 'http://cs.au.dk/~amoeller/XML/xml/recipes.xml' ) ).with { document ->
  def newDoc = new Element( 'collection' ).with { element ->
    addContent document.rootElement.getChild( 'recipe', Namespace.getNamespace( 'http://recipes.org' ) ).detach()
    new Document( element )
  }
  new XMLOutputter().output( newDoc, System.out )
}
0

精彩评论

暂无评论...
验证码 换一张
取 消