[英]Groovy Script to read and transform xml
Need help on Groovy Script. 需要有关Groovy脚本的帮助。 I have the following input xml where this xml will be dynamically populated and we do not have any clues on how many nodes will be populated under
RecordDetails
Node. 我有以下输入xml,其中将动态填充该xml,但对于在
RecordDetails
节点下将填充多少个节点,我们没有任何线索。
Input: 输入:
<?xml version="1.0" encoding="UTF-8"?>
<Record>
<XYZ>
<Header>
<Code>12345</Code>
</Header>
<Details>
<RecID>1</RecID>
<RecordDetail>
<Name>ABC</Name>
<Email>abc@in.com</Email>
<Address>123,acdf</Address>
</RecordDetail>
</Details>
<Details>
<RecID>2</RecID>
<RecordDetail>
<Name>ABC</Name>
<Email>abc@in.com</Email>
</RecordDetail>
</Details>
</XYZ>
</Record>
Output: 输出:
<?xml version="1.0" encoding="UTF-8"?>
<Record>
<Header>
<Code>12345</Code>
</Header>
<Details>
<RecID>1</RecID>
<RecordDetail>
<FieldName>NAME</FieldName>
<FieldValue>ABC</FieldValue>
</RecordDetail>
<RecordDetail>
<FieldName>Email</FieldName>
<FieldValue>ABC@a.com</FieldValue>
</RecordDetail>
</Details>
</Record>
You just need to transform the input xml. 您只需要转换输入xml。
This can be achieved by: 这可以通过以下方式实现:
Looks like you are looking for the later one. 看起来您正在寻找下一个。
Here is the groovy script: 这是常规脚本:
def xml = '''<?xml version="1.0" encoding="UTF-8"?>
<Record>
<XYZ>
<Header>
<Code>12345</Code>
</Header>
<Details>
<RecID>1</RecID>
<RecordDetail>
<Name>ABC</Name>
<Email>abc@in.com</Email>
<Address>123,acdf</Address>
</RecordDetail>
</Details>
<Details>
<RecID>2</RecID>
<RecordDetail>
<Name>ABC</Name>
<Email>abc@in.com</Email>
</RecordDetail>
</Details>
</XYZ>
</Record>'''
def parsedXml = new XmlSlurper().parseText(xml)
def builder = new groovy.xml.StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
def transformedXml = builder.bind {
mkp.xmlDeclaration()
Record {
Header {
Code (parsedXml.'**'.find{ it.name() == 'Code'})
}
def details = parsedXml.'**'.findAll{ it.name() == 'Details'}
details.each { detail ->
Details {
RecID (detail.RecID)
detail.RecordDetail.children().each { fld ->
RecordDetail {
FieldName (fld.name())
FieldValue (fld.text())
}
}
}
}
}
}
println groovy.xml.XmlUtil.serialize(transformedXml)
This can be quickly tried online Demo 可以在线快速尝试演示
Output: 输出:
EDIT: Based on the OP's questions. 编辑:基于OP的问题。
mkp.xmlDeclaration()
- adds <?xml version="1.0"?>
mkp.xmlDeclaration()
-添加<?xml version="1.0"?>
details.each { detail ->
- details is list. details.each { detail ->
-details是列表。 We want to loop thru the each detail. 我们想遍历每个细节。 Each value goes into
detail
. 每个值都会
detail
。
Just similar to for(detail : details)
. 与
for(detail : details)
类似。
fld
is also the same as above. fld
也与上述相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.