使用 groovy 嵌套 XML 到平面 JSON
Nested XML to flat JSON using groovy
我对 groovy 还是个新手。我需要从嵌套的 xml 文件创建一个平面 json 文件。当我尝试创建 JSON.
时,我很难访问 header 字段
这是输入:
<?xml version="1.0"?>
<Data>
<Record>
<Header>Header01</Header>
<Item>
<TEST>E1</TEST>
<TEST2>Free text</TEST2>
</Item>
</Record>
<Record>
<Header>Header02</Header>
<Item>
<TEST>E2</TEST>
<TEST2>Free text</TEST2>
</Item>
<Item>
<TEST>E3</TEST>
<TEST2>Free text</TEST2>
</Item>
</Record>
这是我的代码:
def xml = new XmlSlurper().parse(reader)
def RecordList = xml.'*'.findAll { it->it.name() == 'Record' }
def itemlist = RecordList.'*'.findAll{node ->node.name()== 'Item'}.collect{
row -> row.collectEntries{[TEST: row.TEST.text(), TEST2:row.TEST2.text()]}
}
StringWriter writer = new StringWriter()
StreamingJsonBuilder builder = new StreamingJsonBuilder(writer)
builder {
"Records" itemlist
}
println JsonOutput.prettyPrint(writer.toString())
输出:
{"Records":[{"TEST":"E1","TEST2":"Free text"},{"TEST":"E2","TEST2":"Free text"},
{"TEST":"E3","TEST2":"Free text"}]}
如何使用此方法填充 header 字段?当我创建项目列表时,我无法再访问 xml.
中的 header 字段
不是你的意思的 100%...
你是这个意思吗:
def result = new XmlParser().parse(reader)
.Record
.collectMany { record ->
record.Item.collect {
[ Header: record.Header.text(), Test: it.TEST.text(), Test2: it.TEST2.text() ]
}
}
println new JsonBuilder(result).toPrettyString()
打印:
[
{
"Header": "Header01",
"Test": "E1",
"Test2": "Free text"
},
{
"Header": "Header02",
"Test": "E2",
"Test2": "Free text"
},
{
"Header": "Header02",
"Test": "E3",
"Test2": "Free text"
}
]
我对 groovy 还是个新手。我需要从嵌套的 xml 文件创建一个平面 json 文件。当我尝试创建 JSON.
时,我很难访问 header 字段这是输入:
<?xml version="1.0"?>
<Data>
<Record>
<Header>Header01</Header>
<Item>
<TEST>E1</TEST>
<TEST2>Free text</TEST2>
</Item>
</Record>
<Record>
<Header>Header02</Header>
<Item>
<TEST>E2</TEST>
<TEST2>Free text</TEST2>
</Item>
<Item>
<TEST>E3</TEST>
<TEST2>Free text</TEST2>
</Item>
</Record>
这是我的代码:
def xml = new XmlSlurper().parse(reader)
def RecordList = xml.'*'.findAll { it->it.name() == 'Record' }
def itemlist = RecordList.'*'.findAll{node ->node.name()== 'Item'}.collect{
row -> row.collectEntries{[TEST: row.TEST.text(), TEST2:row.TEST2.text()]}
}
StringWriter writer = new StringWriter()
StreamingJsonBuilder builder = new StreamingJsonBuilder(writer)
builder {
"Records" itemlist
}
println JsonOutput.prettyPrint(writer.toString())
输出:
{"Records":[{"TEST":"E1","TEST2":"Free text"},{"TEST":"E2","TEST2":"Free text"},
{"TEST":"E3","TEST2":"Free text"}]}
如何使用此方法填充 header 字段?当我创建项目列表时,我无法再访问 xml.
中的 header 字段不是你的意思的 100%...
你是这个意思吗:
def result = new XmlParser().parse(reader)
.Record
.collectMany { record ->
record.Item.collect {
[ Header: record.Header.text(), Test: it.TEST.text(), Test2: it.TEST2.text() ]
}
}
println new JsonBuilder(result).toPrettyString()
打印:
[
{
"Header": "Header01",
"Test": "E1",
"Test2": "Free text"
},
{
"Header": "Header02",
"Test": "E2",
"Test2": "Free text"
},
{
"Header": "Header02",
"Test": "E3",
"Test2": "Free text"
}
]