T_Y
T_Y

Reputation: 57

groovy create new xml node

I'd like to create a simple xml node and I looked at the doc from http://docs.groovy-lang.org/latest/html/api/groovy/util/Node.html and write these codes.

    def newbook = new Node(null, 'book', [id:'3'])
    newbook.appendNode(new Node(newbook,'title',[id:'BookId3']))
    newbook.appendNode(new Node(newbook,'author',[id:'3'],'Harper Lee'))

    println groovy.xml.XmlUtil.serialize(newbook)

but the output is

<?xml version="1.0" encoding="UTF-8"?><book id="3">
  <title id="BookId3"/>
  <title/>
  <author id="3">Harper Lee</author>
  <author/>
</book>

it seems to me there are two title tags and author tags get created. why?

I have also tried

    def newbook = new Node(null, 'book', [id:'3'])
    newbook.appendNode(new QName('title'),'BookId3')
    newbook.appendNode(new QName('author'),[id:'3'],'Harper Lee')
    println groovy.xml.XmlUtil.serialize(newbook)

output is

<?xml version="1.0" encoding="UTF-8"?><book id="3">
  <title xmlns="">BookId3</title>
  <author xmlns="" id="3">Harper Lee</author>
</book>

now it looks good but is there a way to remove the namespace?

ideally i would like to have something like this

<book id="3">
  <title>BookId3</title>
  <author id="3">Harper Lee</author>
</book>

and then use it in the replaceNode() method

Upvotes: 2

Views: 8097

Answers (1)

Michael Easter
Michael Easter

Reputation: 24498

Using Groovy 2.4.5, this:

import groovy.util.*

def newbook = new Node(null, 'book', [id:'3'])

new Node(newbook,'title',[id:'BookId3'])
new Node(newbook,'author',[id:'3'],'Harper Lee')

println groovy.xml.XmlUtil.serialize(newbook)

yields this:

<?xml version="1.0" encoding="UTF-8"?><book id="3">
  <title id="BookId3"/>
  <author id="3">Harper Lee</author>
</book>

It may not be obvious, but a closer reading of the doc for the Node constructor reveals that it adds the node to the parent.

Upvotes: 8

Related Questions