python - ElementTree: list.remove(x): x 不在列表中

标签 python xpath elementtree

我有包裹在字符串中的 xml 数据,xml 数据如下所示:

<Root>
   <Header>
      <information>info</information>
   </Header>
   <Main>
      <Product>
         <Name>name1</Name>
         <Description>description1</Description>
      </Product>
      <Product>
         <Name>name2</Name>
         <Description>description2</Description>
      </Product>
   </Main>
</Root>

我想从中删除Header标签

tree = ET.fromstring(xml_string)
tree.remove(tree.findall('.//Header'))

但是它出现错误list.remove(x): x not in list。我做错了什么。谢谢

最佳答案

tree.remove 采用单个元素,而不是 tree.findall 返回的元素列表。您可以为找到的每个 header 调用 tree.remove ,或者仅使用 tree.find 而不是 tree.findall (如果只存在)成为一个标题

关于python - ElementTree: list.remove(x): x 不在列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34357307/

相关文章:

python - 如何通过 Python 的 ElementTree 生成 XML 文件,并在输出中写入注册的命名空间

python - 使用之前的日期从现有列创建新的 Pandas 列

python - 内插 2 个 numpy 数组

python - 为什么 PyTorch 找不到我的 NVIDIA 驱动程序来支持 CUDA?

xml - 如何在 xmlstarlet 的 concat 中打印换行符

python - Selenium Python 在循环中查找当前节点的实际 xPath

javascript - 识别 css 选择器字符串与 XPath 字符串

lxml - 从 XML 中的 etree 的单个元素获取文本

Python ElementTree "no element found"异常

python - 如何将元组转换为不带逗号和括号的值字符串