我试图用Python解析XML。以下是XML结构的示例:
<a>aaaa1
<b>bbbb</b>aaaa2
<c>cccc</c>aaaa3
</a>
可以看出,对于根树a,它有文本“aaaa1”,“aaaa2”在树b和c之间,“aaaa3”在c和a内部之间,我想用“a”:{“aaaaa1”,“aaaa2”,“aaaa3”},“b”:{“bbbbb”},“c”:{“cccc”}。在
xpath/depth标记可能不太复杂,所以这可能是一个更复杂的示例节点。 我用过元素.text, 元素.itertext()和元素.尾部,但“aaaa2”将被视为b的尾部,而“aaaa3”将被视为c的尾部。是否有任何方法可以将文本按上述方式放置?在
^{pr2}$暂时,我尝试通过以下方法标识元素a的所有文本字段,该方法将两个文本与子元素的尾部结合起来:
text_iter = itertools.chain([element.text], (child.tail for child in element.iterchildren()))
text_iter = (text for text in text_iter if isinstance(text, str))
由于我对xmlschema结构和标准不太熟悉,所以不确定这是否总是有效的,以及是否有其他更好的解决方案。在
用Python:3.5测试
可以创建一个函数来收集作为给定父元素的直接子元素的文本节点:
然后对XML中的每个元素调用该函数并以所需的格式打印结果,例如:
^{pr2}$相关问题 更多 >
编程相关推荐