解析根元素中元素之间的XML文本

2024-10-01 07:11:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用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结构和标准不太熟悉,所以不确定这是否总是有效的,以及是否有其他更好的解决方案。在


Tags: 方法text文本child元素示例xmlelement
2条回答

Question: I would like to extract the text in a way that "a": {"aaaa1", "aaaa2", "aaaa3"}, "b": {"bbbb"}, "c": {"cccc"}.


Note: If there are more than one tag <b> or <c> within xml, you have to handle this using a condition!

import lxml.etree as etree

xml = '<a>aaaa1<b>bbbb</b>aaaa2<c>cccc</c>aaaa3</a>'

# Parse xml to tree
tree = etree.fromstring(xml)
#root = tree.getroot()

# In this example, the first tag is the root Element
root = tree.tag

# Init result dict with this first Element tag:[text]
result = {tree.tag:[tree.text]}

# Loop every Element in the tree
for element in tree:
    # Add this element to result tag:text
    result.setdefault(element.tag, element.text)

    # If this element has a .tail, append it to the root:[]
    if element.tail:
        result[root].append(element.tail)

print("result:{}".format(result))
>>>result:{'c': 'cccc', 'b': 'bbbb', 'a': ['aaaa1', 'aaaa2', 'aaaa3']}

用Python:3.5测试

可以创建一个函数来收集作为给定父元素的直接子元素的文本节点:

def read_element(e):
    return {e.tag: [t.strip() for t in e.xpath("text()")]}

然后对XML中的每个元素调用该函数并以所需的格式打印结果,例如:

^{pr2}$

相关问题 更多 >