获取XML文件中元素外部的注释位置-Python

获取XML文件中元素外部的注释位置-Python,python,xml,list,Python,Xml,List,我有一个XML文件“example.XML”,其格式与以下类似: <ParentOne> <!-- Comment 1--> <SiblingOneA>This is Sibling One A</SiblingOneA> <SiblingTwoA> <!-- Comment --> <ChildOneA>Value of child one A <!-- Comment 2--&

我有一个XML文件“example.XML”,其格式与以下类似:

<ParentOne> <!-- Comment 1-->
   <SiblingOneA>This is Sibling One A</SiblingOneA> 
   <SiblingTwoA> <!-- Comment -->
      <ChildOneA>Value of child one A <!-- Comment 2--></ChildOneA>
      <!-- <break>Comment between tags</break>-->
      <ChildTwoA>Value of child two A</ChildTwoA>
      <ChildThreeA>Value of child three A</ChildThreeA>
      <!-- <break>Another comment between tags</break>-->
      <ChildFourA>Value of child four A</ChildFourA>
   </SiblingTwoA>
</ParentOne>
此代码返回:

[<!-- Comment 1-->]
[]
[<!-- Comment -->, <!-- <break>Comment between tags</break>-->, <!-- <break>Another comment between tags</break>-->]
[<!-- Comment 2-->]
[]
[]
[]
[]
[]
[, ]
[]
[]
[]
[]
我理解为什么列表中的第三个元素(对应于SiblingTwoA)返回3条注释,因为2条break注释在技术上对应于该标记。但是,有没有一种方法可以让我发现第一个中断注释在ChildOneA和ChildTwoA标记之间,第二个在ChildTwoA和ChildFourA标记之间


如果需要,很高兴澄清,因为这可能有点让人困惑。

我相信您正在寻找这样的产品:

for tag in doc.xpath('//*'):
    comment = tag.xpath('./comment()')
    if comment:
        for c in comment: 
            bef = c.xpath('./preceding-sibling::*[1]')
            aft = c.xpath('./following-sibling::*[1]')
            if bef:
                print(c,'is between',bef[0].tag,'and ',aft[0].tag)
输出:

<!-- <break>Comment between tags</break>--> is between ChildOneA and  ChildTwoA
<!-- <break>Another comment between tags</break>--> is between ChildThreeA and  ChildFourA
介于ChildOneA和ChildTwoA之间
在ChildThree和ChildFour之间
<!-- <break>Comment between tags</break>--> is between ChildOneA and  ChildTwoA
<!-- <break>Another comment between tags</break>--> is between ChildThreeA and  ChildFourA