-3

与我真正想提出的问题相比,标题相当简单,但我不太确定如何措辞。对于我正在制作的 XML 解析模块,我需要它根据 XML 文档的确切结构添加键和属性,例如:

<Person>
    <Name>Someone</Name>
    <Age>25</Age>
    <Skills>
    <Skill>Projectile vomiting</Skill>
    </Skills> 
</Person>

应该返回:

{ "Person" : { "Name" : "Someone", "Age" : "25", "Skills" : { "Skill" : "Projectile vomiting"}}}

...在程序不知道 XML 文档的确切结构的情况下。它可以有任意数量的属性,任意数量的嵌套属性。

使用

Dict["key"]["anotherkey"]["yetanotherkey"] = Value

不起作用,因为我不知道 XML 文档是否使用 3 个属性嵌套,或者这些属性嵌套是否包含更多嵌套。

我的想法是每次解析器遇到嵌套的开头时“打开一个节点”,换句话说,如果解析器到达

<Skill> 

它会在其中分配属性

<Skills> and </Skills> 

到 Dict["Person"]["Skills"],以及何时

</Skills>

遇到,它将“关闭”节点,并继续将属性分配给 Dict["Person"],但我不知道如何实现这一点(但我可以获得文档的所有值、属性和节点)。

如上所示,如何在不知道 XML 文档的确切结构的情况下以正确的格式嵌套字典?

4

1 回答 1

2

You can use a stack corresponding to the point at which you are in the XML document. Each time you encounter an open tag you push it on to the stack and begin filling attributes for the value at stack.peek(). When you encounter a closing tag, you pop the last tag off the stack and know that you'll now be filling attributes for the tag at the new top of the stack.

于 2012-12-09T00:19:12.860 回答