跳绳;嵌套标记";使用Python解析XML时
我目前有一个XML文件,我想用Python解析它。我正在使用Python的元素树,它工作得很好,只是我有一个问题 该文件当前看起来像:跳绳;嵌套标记";使用Python解析XML时,python,xml,elementtree,Python,Xml,Elementtree,我目前有一个XML文件,我想用Python解析它。我正在使用Python的元素树,它工作得很好,只是我有一个问题 该文件当前看起来像: <Instance> <TextContent> <Sentence>Hello, my name is John and his <Thing>name</Thing> is Tom.</Sentence> </TextContent> <Instance
<Instance>
<TextContent>
<Sentence>Hello, my name is John and his <Thing>name</Thing> is Tom.</Sentence>
</TextContent>
<Instance>
提前谢谢。我稍微更改了您的源XML文件,因此句子中包含两个 子元素:
<Instance>
<TextContent>
<Sentence>Hello, my <Thing>name</Thing> is John and his <Thing>name</Thing> is Tom.</Sentence>
</TextContent>
</Instance>
要查看所有直接子体文本节点的列表,请运行:
lst = list(allTextNodes(st))
结果是:
['Hello, my ', ' is John and his ', ' is Tom.']
但要将连接的文本作为单个变量,请运行:
txt = ''.join(allTextNodes(st))
获取:您好,我的是约翰,他的是汤姆。
(注意双空格,
“环绕”两个省略的事物元素。文本部分(“是汤姆”)在
结束标记之后出现的是该元素的尾部。请参见,谢谢!我没有意识到这一点。不幸的是,有多个嵌套标记,因此如果有办法完全忽略它们,也会很有帮助,但似乎我必须手动编写规则。请尝试itertext()
:您是否可以编辑您的问题以添加一个包含多个嵌套标记的示例,以及所需的输出?
['Hello, my ', ' is John and his ', ' is Tom.']
txt = ''.join(allTextNodes(st))