我在许多网站上看到了MarkupBuilder xml创建者的普遍使用。例如:
def xmlWriter = new StringWriter()
def xmlMarkup = new MarkupBuilder(xmlWriter)
xmlMarkup.movie(id: "2", "the godfather")
println(xmlWriter.toString())会给出这样的东西:
<movie id='2'>the godfather</movie>我的问题是:是否有一种好的方法可以使用MarkupBuilder使用从方法中提取的变量来编写xml?
我必须设法用以下代码添加根访问:
createXml(root){
def xmlWriter = new StringWriter()
def xmlMarkupBuilder = new MarkupBuilder(xmlStringWriter)
xmlMarkupBuilder.createNode(root)
xmlMarkupBuilder.nodeCompleted(null,root)
}但我敢肯定肯定还有另外一种干净的方法。如果只知道父节点的名称,如何添加新节点?
最后我用java DocumentBuilder做了这个,
XmlData(xmlPath, rootNodeName){
this.xmlPath = xmlPath
xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()
def rootNode=xmlDoc.createElement(rootNodeName)
xmlDoc.appendChild(rootNode)
}
def addNode(parentNodeName,nodeName,nodeValue,attributes){
def newNode = xmlDoc.createElement(nodeName)
if(nodeValue!=null){
def newTextNode = xmlDoc.createTextNode(nodeValue)
newNode.appendChild(newTextNode)
}
if(attributes!=null){
attributes.each{key,value ->
newNode.setAttribute($key,$value)
}
}
def nodeList = xmlDoc.getElementsByTagName(parentNodeName)
nodeList.item(nodeList.getLength()-1).appendChild(newNode)
}但是,如果有一种使用MarkupBuilder或MarkupBuilderHelper的更干净的方法,我希望使用这一方法。我想得到的代码是:
输入:
def xmlWriter = new XmlWriter("rootNode")
xmlWriter.addNode("rootNode","",null)
xmlWriter.addNode("rootNode","child2",null)
xmlWriter.addNode("child1","child11","text1")
xmlWriter.addNode("child1","child12","text2")
xmlWriter.addNode("child2","child21","text3")
xmlWriter.addNode("child2","child22","text4")方法:
class XmlWriter{
createXml(root){
def xmlWriter = new StringWriter()
def xmlMarkupBuilder = new MarkupBuilder(xmlStringWriter)
xmlMarkupBuilder.createNode(root)
xmlMarkupBuilder.nodeCompleted(null,root)
}
def addNode(parentNodeName,nodeName,nodeValue,attributes){
???
}
}输出:
<rootNode>
<child1>
<child11>test1</child11>
</child12>test2</child12>
</child1>
<child2>
<child21>test3</child21>
</child22>test4</child22>
</child2>
</rootNode>注意:我没有考虑到可能存在于nodeList项中的几个项,因为在我的xml中,这在目前是不可能的。
发布于 2015-10-23 13:42:29
这里有一个方法来做我认为你想做的事..。
给定一些XML:
def xml = '''<root>
| <node>
| <anotherNode some="thing">
| Woo
| </anotherNode>
| <stuff>
| </stuff>
| <node>
| </node>
| <anotherNode some="thing">
| Woo
| </anotherNode>
| <stuff>
| </stuff>
| </node>
|</root>'''.stripMargin()并且给定父节点的名称、新子节点的名称、它的属性和文本内容:
def parentName = 'stuff'
def nodeName = 'things'
def nodeContent = 'text'
def attributes = [ tim: 'yates' ]我们可以用XmlParser解析XML。
import groovy.xml.*
def root = new XmlParser().parseText(xml)然后找到所有名为parentName的节点,并向每个节点追加一个新节点:
root.'**'.findAll { it.name() == parentName }
.each {
it.appendNode(new Node(it, nodeName, attributes, nodeContent))
}然后,打印出xml应该显示它们在那里:
println XmlUtil.serialize(root)https://stackoverflow.com/questions/33299972
复制相似问题