문제

the title is rather simple compared to the question I really want to make, but I'm not quite sure how to word it. For an XML parsing module I'm making, I need it to add keys and attributes according to the exact structure of the XML document, for example:

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

Should return:

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

...without the program knowing the exact structure of the XML document. It could have any number of attributes, any number of nested attributes.

Using

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

won't work, because I have no idea if the XML document uses 3 attribute nests, or if those nests of attributes contain more nests.

The idea I had was to "open a node" every time the parser encounters the beginning of a nest, in other words, if the parser reached

<Skill> 

it would assign attributes within

<Skills> and </Skills> 

to Dict["Person"]["Skills"], and when

</Skills>

was encountered, it would "close" the node, and continue assigning attributes to Dict["Person"], but I have no idea how to implement this (but I can get all the values, attributes, and nodes of the document).

How can I nest the dictionaries in the correct format without knowing the exact structure of the XML document, as shown above?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top