acutal xml是:
<prnReq>
<ltrPrnReqs>
<ltrPrnReq>
<ltrData>
<Postal>910060121</Postal>
<Amt>514.17</Amt>
</ltrData>
</ltrPrnReq>
</ltrPrnReqs>
</prnReq>
最终的XML必须只是&#39; ltrData&#39;:
<ltrData>
<Postal>910060121</Postal>
<Amt>514.17</Amt>
</ltrData>
在当前代码下面,我需要仅使用标记创建新文件,但代码未运行。
import groovy.xml.QName
import groovy.xml.StreamingMarkupBuilder
import groovy.xml.XmlUtil
def xmlString = """
<prnReq>
<ltrPrnReqs>
<ltrPrnReq>
<ltrData>
<Postal>910060121</Postal>
<Amt>514.17</Amt>
</ltrData>
</ltrPrnReq>
</ltrPrnReqs>
</prnReq>"""
def xml1 = new XmlSlurper().parseText(xmlString)
def ltrD = xml1.'**'.find{it.name() == 'ltrData'}.text()
def builder = new StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
def xml2 = builder.bindNode (ltrD)
def file1 = new File('C:\\Temp\\out\\ltrData.xml')
assert XmlUtil.serialize(xml2)
file1.write(xml2,'UTF-8'))
嗨@Rao,我刚刚更新了内容。当我尝试应用建议的解决方案时,我收到一个错误:&#34; [致命错误]:1:1:文件过早结束。&#34;。 所以我相信我仍然在做错内容。您能否看看如何获得正确的语法以获得上述两个新元素?非常感谢
答案 0 :(得分:1)
您应该可以使用StreamingMarkupBuilder
执行此操作。并按照在线评论:
import groovy.xml.StreamingMarkupBuilder
import groovy.xml.XmlUtil
def xmlString = """<prnReq>
<ltrPrnReqs>
<ltrPrnReq>
<ltrData>
<Postal>910060121</Postal>
<Amt>514.17</Amt>
</ltrData>
</ltrPrnReq>
</ltrPrnReqs>
</prnReq>"""
//Extract the data you needed from existing xml
def xml1 = new XmlSlurper().parseText(xmlString)
def ltrData1 = xml1.'**'.find{it.name() == 'ltrData'}
def nodes = ltrData1.children()*.name()
//Build the output xml
def xml = new StreamingMarkupBuilder().bind {
ltrData {
nodes.each { "$it"(ltrData1."$it".text()) }
}
}
def file = new File('C:/Temp/out/letter_PQC301.xml')
println XmlUtil.serialize(xml)
file.write(XmlUtil.serialize(xml),'UTF-8')
您可以在线快速尝试 demo
编辑:优化的解决方案。请注意,以下使用时不使用StreamingMarkupBuilder
import groovy.xml.StreamingMarkupBuilder
import groovy.xml.XmlUtil
def xmlString = """<prnReq>
<ltrPrnReqs>
<ltrPrnReq>
<ltrData>
<Postal>910060121</Postal>
<Amt>514.17</Amt>
</ltrData>
</ltrPrnReq>
</ltrPrnReqs>
</prnReq>"""
//Extract the data you needed from existing xml
def xml1 = new XmlSlurper().parseText(xmlString)
def ltrData1 = xml1.'**'.find{it.name() == 'ltrData'}
def file = new File('C:/Temp/out/letter_PQC301.xml')
println XmlUtil.serialize(ltrData1)
file.write(XmlUtil.serialize(ltrData1),'UTF-8')