簡體   English   中英

xml.etree.ElementTree .remove

[英]xml.etree.ElementTree .remove

我正在嘗試使用 remove 從 Xml.Alto 文件中remove標簽。 我的 Alto 文件如下所示:

<alto xmlns="http://www.loc.gov/standards/alto/ns-v4#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/standards/alto/ns-v4# http://www.loc.gov/standards/alto/v4/alto-4-2.xsd">   <Description>
    <MeasurementUnit>pixel</MeasurementUnit>
    <sourceImageInformation>
      <fileName>filename</fileName>
    </sourceImageInformation>   
</Description>   
<Layout>
    <Page>
      <PrintSpace>
        <TextBlock>
          <Shape><Polygon/></Shape>
          <TextLine>
            <Shape><Polygon/></Shape>
        <String CONTENT="ABCDEF" HPOS="1234" VPOS="1234" WIDTH="1234" HEIGHT="1234" />
          </TextLine>
        </TextBlock>
      </PrintSpace>
    </Page>   
</Layout> 
</alto>

我的代碼是:

import xml.etree.ElementTree as ET
tree = ET.parse("file.xml")
root = tree.getroot()
ns = {'alto': 'http://www.loc.gov/standards/alto/ns-v4#'}
ET.register_namespace("", "http://www.loc.gov/standards/alto/ns-v4#")
for Test in root.findall('.//alto:TextBlock', ns):
    root.remove(Test)
    
tree.write('out.xml', encoding="UTF-8", xml_declaration=True)

這是我得到的錯誤:

ValueError: list.remove(x): x not in list

非常感謝您的幫助💐

ElementFather.remove(ElementChild)僅在ElementChildElementFather的子元素時才有效。 在您的情況下,您必須從 PrintSpace 調用 remove。

import xml.etree.ElementTree as ET
tree = ET.parse("file.xml")
root = tree.getroot()
ns = {'alto': 'http://www.loc.gov/standards/alto/ns-v4#'}
ET.register_namespace("", "http://www.loc.gov/standards/alto/ns-v4#")

for Test in root.findall('.//alto:TextBlock', ns):
    PrintSpace = root.find('.//alto:PrintSpace',ns)
    PrintSpace.remove(Test)
    
tree.write('out.xml', encoding="UTF-8", xml_declaration=True)

注意:此代碼只是一個有效解決方案的示例,您可以對其進行改進。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM