使用Groovy将带有命名空间的XML节点添加到现有文档

时间:2014-04-09 22:31:31

标签: xml groovy rss

如何将带有命名空间前缀的xml节点添加到现有文档?如果可能的话,我想建立我迄今为止所拥有的东西:

def rss = new XmlParser().parse(xmlFile)

rss.channel + {
item {
    title("My super atom feed")
    link(href:"http://www.thecoderscorner.com")
    description("content of rss item goes here")
    guid(isPermaLink: "false", "8452")  
}
}

我想在上面的项目中添加以下内容:

<event:startDate>Tue, 8 Apr 2014 15:00:00 PDT</event:startDate>
<event:endDate>Tue, 8 Apr 2014 18:00:00 PDT</event:endDate>
<event:location>1234 Mrak Hall</event:location>
<event:isAllDay>false</event:isAllDay>

1 个答案:

答案 0 :(得分:0)

你应该可以这样做:

def rss = new XmlParser().parseText( xml )
rss.channel.item + {
    item {
        title("My super atom feed")
        link(href:"http://www.thecoderscorner.com")
        description("content of rss item goes here")
        guid(isPermaLink: "false", "8452")  
        'event:startDate'( "Tue, 8 Apr 2014 15:00:00 PDT" )
        'event:endDate'( "Tue, 8 Apr 2014 18:00:00 PDT" )
        'event:location'( "1234 Mrak Hall" )
        'event:isAllDay'( false )
    }
}
String output = new StringWriter().with { xmlOutput ->
    new XmlNodePrinter( new PrintWriter( xmlOutput ) ).with { printer ->
        preserveWhitespace = true
        expandEmptyElements = true
        printer.print( rss )
    }
    xmlOutput.toString()
}

println output