- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个使用 XML 命名空间的文档,我想为其增加 /group/house/dogs
一个:(文件名为 houses.xml
)
<?xml version="1.0"?>
<group xmlns="http://dogs.house.local">
<house>
<id>2821</id>
<dogs>2</dogs>
</house>
</group>
我当前使用以下代码的结果是:(创建的文件名为 houses2.xml
)
<ns0:group xmlns:ns0="http://dogs.house.local">
<ns0:house>
<ns0:id>2821</ns0:id>
<ns0:dogs>3</ns0:dogs>
</ns0:house>
</ns0:group>
我想解决两件事(如果可以使用 ElementTree。如果不能,我将非常感谢您就我应该使用什么提出建议):
<?xml version="1.0"?>
行。总而言之,我不想把文件弄得乱七八糟。
生成上述结果的当前代码(除上述缺陷外有效)如下。
我创建了一个实用函数,它使用 ElementTree 加载 XML 文件并返回 elementTree 和命名空间(因为我不想对命名空间进行硬编码,并且愿意承担它所暗示的风险):
def elementTreeRootAndNamespace(xml_file):
from xml.etree import ElementTree
import re
element_tree = ElementTree.parse(xml_file)
# Search for a namespace on the root tag
namespace_search = re.search('^({\S+})', element_tree.getroot().tag)
# Keep the namespace empty if none exists, if a namespace exists set
# namespace to {namespacename}
namespace = ''
if namespace_search:
namespace = namespace_search.group(1)
return element_tree, namespace
这是我的代码,用于更新狗的数量并将其保存到新文件 houses2.xml
:
elementTree, namespace = elementTreeRootAndNamespace('houses.xml')
# Insert the namespace before each tag when when finding current number of dogs,
# as ElementTree requires the namespace to be prefixed within {...} when a
# namespace is used in the document.
dogs = elementTree.find('{ns}house/{ns}dogs'.format(ns = namespace))
# Increase the number of dogs by one
dogs.text = str(int(dogs.text) + 1)
# Write the result to the new file houses2.xml.
elementTree.write('houses2.xml')
最佳答案
针对此问题的基于 XML 的解决方案是为 ElementTree 编写一个辅助类:
它有一个主要缺点:
我的帮助类示例:
from xml.etree import ElementTree as ET
import re
class ElementTreeHelper():
def __init__(self, xml_file_name):
xml_file = open(xml_file_name, "rb")
self.__parse_xml_declaration(xml_file)
self.element_tree = ET.parse(xml_file)
xml_file.seek(0)
root_tag_namespace = self.__root_tag_namespace(self.element_tree)
self.namespace = None
if root_tag_namespace is not None:
self.namespace = '{' + root_tag_namespace + '}'
# Register the root tag namespace as having an empty prefix, as
# this has to be done before parsing xml_file we re-parse.
ET.register_namespace('', root_tag_namespace)
self.element_tree = ET.parse(xml_file)
def find(self, xpath_query):
return self.element_tree.find(xpath_query)
def write(self, xml_file_name):
xml_file = open(xml_file_name, "wb")
if self.xml_declaration_line is not None:
xml_file.write(self.xml_declaration_line + '\n')
return self.element_tree.write(xml_file)
def __parse_xml_declaration(self, xml_file):
first_line = xml_file.readline().strip()
if first_line.startswith('<?xml') and first_line.endswith('?>'):
self.xml_declaration_line = first_line
else:
self.xml_declaration_line = None
xml_file.seek(0)
def __root_tag_namespace(self, element_tree):
namespace_search = re.search('^{(\S+)}', element_tree.getroot().tag)
if namespace_search is not None:
return namespace_search.group(1)
else:
return None
def __main():
el_tree_hlp = ElementTreeHelper('houses.xml')
dogs_tag = el_tree_hlp.element_tree.getroot().find(
'{ns}house/{ns}dogs'.format(
ns=el_tree_hlp.namespace))
one_dog_added = int(dogs_tag.text.strip()) + 1
dogs_tag.text = str(one_dog_added)
el_tree_hlp.write('hejsan.xml')
if __name__ == '__main__':
__main()
输出:
<?xml version="1.0"?>
<group xmlns="http://dogs.house.local">
<house>
<id>2821</id>
<dogs>3</dogs>
</house>
</group>
如果有人对此解决方案有改进,请不要犹豫,获取代码并加以改进。
关于Python:使用 ElementTree 更新 XML 文件,同时尽可能保留布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9579700/
我正在尝试从字符串构建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 的质量。在某些情况下是: ... 在其他方面我得到: ... 我想我也应该处理 ... 整个架构都是相同的,我只需要一个解析器来处理它。我该如何处理所有这些
我是一名优秀的程序员,十分优秀!