我会尝试解释我尽力做到最好的事情,但如果它像泥巴一样清楚我会道歉。
我试图建立一个基于骨架的XML结构,这将是几层深度的,我可能需要从我将要添加数据的父元素创建不同的元素。例如,我可能有:
<List>
<Mailing>
<MailTo>
<MailingInfo>
<FirstName/>
<LastName/>
<Address1/>
<City/>
<State/>
<Zip/>
<Party>
<Guests>
<Guest>
<FirstName/>
<LastName/>
对于每个元素,我都在迭代子节点,并捕获特定的元素名称以手动添加数据,但我为每个深度创建了许多代码块。我的代码看起来像是:
# +7
for levelSeven in xmlSkeleton[rootChild.tag][subRootChild.tag][levelThree.tag][levelFour.tag][levelFive.tag][levelSix.tag].iterchildren():
levelSevenSize = len([el.tag for el in xmlSkeleton[rootChild.tag][subRootChild.tag][levelThree.tag][levelFour.tag][levelFive.tag][levelSix.tag][levelSeven.tag].iterdescendants() if el.tag != None])
if levelSevenSize == 0:
levelSevenElement = objectify.SubElement(levelSixElement, levelSeven.tag)
elif levelSevenSize > 0:
levelSevenElement = objectify.SubElement(levelSixElement, levelSeven.tag)
# +8
for levelEight in xmlSkeleton[rootChild.tag][subRootChild.tag][levelThree.tag][levelFour.tag][levelFive.tag][levelSix.tag][levelSeven.tag].iterchildren():
levelEightSize = len([el.tag for el in xmlSkeleton[rootChild.tag][subRootChild.tag][levelThree.tag][levelFour.tag][levelFive.tag][levelSix.tag][levelSeven.tag][levelEight.tag].iterdescendants() if el.tag != None])
if levelEightSize == 0:
levelEightElement = objectify.SubElement(levelSevenElement, levelEight.tag)
elif levelEightSize > 0:
levelEightElement = objectify.SubElement(levelSevenElement, levelEight.tag)
# +9
for levelNine in xmlSkeleton[rootChild.tag][subRootChild.tag][levelThree.tag][levelFour.tag][levelFive.tag][levelSix.tag][levelSeven.tag][levelEight.tag].iterchildren():
levelNineSize = len([el.tag for el in xmlSkeleton[rootChild.tag][subRootChild.tag][levelThree.tag][levelFour.tag][levelFive.tag][levelSix.tag][levelSeven.tag][levelEight.tag][levelNine.tag].iterdescendants() if el.tag != None])
if levelNineSize == 0:
levelNineElement = objectify.SubElement(levelEightElement, levelNine.tag)
elif levelNineSize > 0:
levelNineElement = objectify.SubElement(levelEightElement, levelNine.tag)
else:
pass
我真的希望有更好的方法来迭代XML骨架(针对特定于架构的结构)并在捕获特定元素时添加数据,例如&#34; MailingInfo&#34;或&#34; Guestt&#34;从字典中添加子元素的特定详细信息。我尝试了许多混合物,但还没有成功。我不确定一个类在这里是否有益,或者甚至不知道如何处理那些像这样的荒谬数量的嵌套代码块。
目标是能够继续生成XML结构并在骨架更改时捕获相同的元素。任何输入都会受到赞赏!