gpt4 book ai didi

python - 从 Python 中的特定 XML 节点检索注释

转载 作者:太空宇宙 更新时间:2023-11-04 11:08:00 26 4
gpt4 key购买 nike

我有以下“example.xml”文件

<?xml version="1.0" encoding="UTF-8"?>
<root>
<tag1>
<tag2>tag2<!-- comment = “this is the tag1 comment”--></tag2>
<tag3>
<tag4>tag4<!-- comment = “this is the tag4 comment”--></tag4>
</tag3>
</tag1>
</root>

我想检索对特定节点的评论。目前,我只能使用以下命令从文件中检索所有评论

from lxml import etree

tree = etree.parse("example.xml")
comments = tree.xpath('//comment()')
print(comments)

正如预期的那样,这将从列表中的文件返回所有上述评论:

[<!-- comment = \u201cthis is the tag1 comment\u201d-->, <!-- comment = \u201cthis is the tag4 comment\u201d-->]

但是,如何以及在何处明确指定要检索其评论的节点?例如,我如何指定某处 tag2只返回 <!-- comment = \u201cthis is the tag4 comment\u201d-->

编辑

我有一个用例,我需要遍历 XML 文件的每个节点。如果迭代器到达一个节点,该节点有多个带有注释的子节点,它会返回其子节点的所有注释。例如,考虑以下“example2.xml”文件:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<tag1>
<tag2>
<tag3>tag3<!-- comment = “this is the tag3 comment”--></tag3>
<tag4>tag4<!-- comment = “this is the tag4 comment”--></tag4>
</tag2>
</tag1>
<tag1>
<tag2>
<tag3>tag3<!-- comment = “this is the tag3 comment”--></tag3>
<tag4>tag4<!-- comment = “this is the tag4 comment”--></tag4>
</tag2>
</tag1>
</root>

如果我按照上面相同的步骤,当循环迭代到tag1/tag2时, 它返回 tag3 和 tag4 的所有评论。

即:

from lxml import etree

tree = etree.parse("example2.xml")
comments = tree.xpath('tag1[1]/tag2//comment()')
print(comments)

返回

[<!-- comment = \u201cthis is the tag3 comment\u201d-->, <!-- comment = \u201cthis is the tag4 comment\u201d-->]

因此我的两个问题是:

  1. 我怎样才能只返回直接节点的评论而不包括它的任何子节点?
  2. 由于结果以列表的形式返回,我如何从所述列表中检索评论的值/文本?

最佳答案

需要指定节点:

tree = etree.parse("example.xml")
comments = tree.xpath('//tag2/comment()')
print(comments)

输出:

[<!-- comment = “this is the tag1 comment”-->]

编辑:

对于嵌套结构,您需要遍历重复标签:

tag2Elements = tree.xpath('//tag1/tag2')
for t2 in tag2Elements:
t3Comment = t2.xpath('tag3/comment()')
print(t2, t3Comment)

输出:

<Element tag2 at 0x1066b69b0> [<!-- comment = “this is the tag3 comment”-->]
<Element tag2 at 0x1066b6960> [<!-- comment = “this is the tag3 comment”-->]

关于python - 从 Python 中的特定 XML 节点检索注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58959574/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com