我正在尝试基于level
表示路径的元素从平面 XML 创建嵌套层次结构。每个level
元素及其所属的兄弟姐妹(名称和编号不同)都应该被包装在一个“记录”元素中,从而创建一个树结构。
从这个来源(简化):
<?xml version="1.0" encoding="UTF-8"?>
<record>
<level>first</level>
<unitid>0001</unitid>
<a-few-more-siblings/>
<level>first/second</level>
<unitid>0002</unitid>
<many-more-siblings/>
<level>first/second/third</level>
<unitid>0003a</unitid>
<some-more-siblings/>
<level>first/second/third</level>
<unitid>0003b</unitid>
<many-more-siblings/>
<level>first/second/third</level>
<unitid>0003c</unitid>
<some-more-siblings/>
<level>first</level>
<unitid>0004</unitid>
<again-more-siblings/>
</record>
我想生成以下所需的输出:
<Record level="first">
<level>first</level>
<unitid>001</unitid>
<a-few-more-siblings/>
<Record level="second">
<level>second</level>
<unitid>002</unitid>
<many-more-siblings/>
<Record level="third">
<level>third</level>
<unitid>003a</unitid>
<some-more-siblings/>
</Record>
<Record level="third">
<level>third</level>
<unitid>003b</unitid>
<many-more-siblings/>
</Record>
<Record level="third">
<level>third</level>
<unitid>003c</unitid>
<some-more-siblings/>
</Record>
</Record>
</Record>
<Record level="first">
<level>first</level>
<unitid>0004</unitid>
<again-more-siblings/>
</Record>
到目前为止,我能生产的最接近的是:
<record level="first">
<level>first</level>
<unitid>0001</unitid>
<some-other-siblings/>
<record level="second">
<level>first/second</level>
<unitid>0002</unitid>
<some-other-siblings/>
<record level="third">
<level>first/second</level>
<unitid>0002</unitid>
<some-other-siblings/>
<level>first/second/third</level>
<unitid>0003a</unitid>
<some-other-siblings/>
</record>
<record level="third">
<level>first/second</level>
<unitid>0002</unitid>
<some-other-siblings/>
<level>first/second/third</level>
<unitid>0003a</unitid>
<some-other-siblings/>
<level>first/second/third</level>
<unitid>0003b</unitid>
<some-other-siblings/>
</record>
<record level="third">
<level>first/second/third</level>
<unitid>0003c</unitid>
<some-other-siblings/>
</Record>
</record>
</record>
(第三层不受欢迎的兄弟姐妹额外缩进;0004
第一层没有出现)
我尝试了针对类似问题提出的不同方法变体(“从平面到分层”、“跟随兄弟姐妹直到”等),但最终要么在某个位置打印了太多兄弟姐妹,要么只输出第一条记录在第三层。
任何帮助是极大的赞赏。