- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
现在尝试了几个不同的库,我认为我很接近,但无法解决这个问题。
我有一个 XML 文件,其中包含一些我想要删除的嵌套表。这些是 XML 层次结构中的几个级别。
到目前为止我已经尝试过这个...
import xml.etree.ElementTree as ET
import os
tree = ET.parse('/Users/me/file.xml')
root = tree.getroot()
for sect1 in root.findall('section1'):
for sect2 in sect1.iter() :
if sect2.tag == 'table':
sect1.remove(sect2)
但是我收到错误:
ValueError: list.remove(x): x not in list
我可以使用以下代码成功地从层次结构的顶层删除文档的各个部分:
import xml.etree.ElementTree as ET
import os
tree = ET.parse('/Users/me/file.xml')
root = tree.getroot()
for sect1 in root.findall('section1'):
root.remove(sect1)
我只是想念如何删除距离顶层更远的元素。
非常感谢任何帮助。
最佳答案
使用这个:
for sect1 in root.findall('.//section1'):
root.remove(sect1)
.//
从第一个元素的所有子section1 元素中进行选择。您可以使用 './section1/section2'
更具体地选择元素,也可以使用 ./section1[@Name="SomeValueForNameAttribute"]'
选择具有特定属性的元素如果您想了解更多信息,这称为 xpath,元素树提供的精简版本已记录在 here 中。
关于python - 使用 elementtree Python 从 XML 中删除元素和子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52519610/
我正在尝试从字符串构建ElementTree。当我执行以下操作时(如 Python ElementTree: Parsing a string and getting ElementTree inst
我正在使用 elementtree.ElementTree.iterparse 来解析大型 (371 MB) xml 文件。 我的代码基本上是这样的: outf = open('out.txt', '
有没有办法在 elementtree.ElementTree 中忽略标记名称中的 XML 命名空间? 我尝试打印所有 technicalContact 标签: for item in root.get
我使用 xml.etree.elementtree.Element 创建了一个 XML 文档,并想使用 ElementTree.write() 函数打印它但是出来的声明标签是 虽然我需要用双引号引起
这个问题已经有答案了: What is the best way to remove accents (normalize) in a Python unicode string? (14 个回答)
我想为此处元素国家/地区新加坡旁边的元素创建子元素。 假设我的 test.xml 文件如下所示 2008 141100
我正在使用ElementTree加载一系列 XML 文件并解析它们。解析文件时,我将从其中获取一些数据(标题和文本段落)。然后我需要获取一些存储在 XML 中的文件名。它们包含在名为 ContentI
我必须将多个 XML 文件合并为一个。此外,新文件的结构也不同。这是我的“旧”结构: 1
我正在解析一个 xml 文件:http://pastebin.com/fw151jQN我希望在副本中读取它的大部分内容并将其写入一个新文件,其中一些已修改,很多未修改,还有很多被忽略。作为初始阶段,我
这是 XML: TARGET_NAME_1 5 a string goes here TARGET_NA
from lxml import etree from xml.etree.ElementTree import Element, SubElement, dump listing = Element
当涉及到模块/库时,为了可读性,我喜欢在 python 中使用完整的命名空间。我想知道为什么这对 xml 库不起作用。我认为 import xml 还将导入 etree 和命名空间中的所有其他内容。至
这里是 Python 菜鸟。想知道删除所有 updated 属性值为 true 的“profile”标签的最干净、最好的方法是什么。 我已经尝试了下面的代码,但它抛出了:SyntaxError("ca
尝试从 xml 文档中删除元素时出现以下错误。“ValueError: list.remove(x): x 不在列表中”这是代码,错误发生在删除的行上。 import xml.etree.Elemen
所以我必须编写一个“重复检查器”来比较两个 XML,看看它们是否相同(包含相同的数据)。现在因为它们来自同一个类并且是从 XSD 结构中生成的,所以内部元素的顺序很可能是相同的。 我能想到的进行重复检
我有一个 XML 文档,我正在使用 ElementTree 阅读和附加该文档。这有多个命名空间声明。据我所知,ElementTree 只允许声明一个全局命名空间: ET.register_namesp
从这里开始: stuff
我是 ElementTree 的新手。我正在尝试获取 来自 XML 响应的值。 以下代码对我不起作用。如何提取 中的值?我不确定号码在哪里 53是从这里来的。 ... r = req
以下代码: import xml.etree.ElementTree as ET xml = '''\ ''' root = ET.fromstring(xml)
我无法控制我获得的 XML 的质量。在某些情况下是: ... 在其他方面我得到: ... 我想我也应该处理 ... 整个架构都是相同的,我只需要一个解析器来处理它。我该如何处理所有这些
我是一名优秀的程序员,十分优秀!