我正在将 BytesIO SVG 数据解析为元素树。我开始于:
tree = ET.parse(svg)
root = tree.getroot()
根在哪里:
<Element '{http://www.w3.org/2000/svg}svg' at 0x000001E19B2E54E0>
我的目标是使用 findall() 并操作结果元素列表:
for elem in root.findall(".//"):
# manipulate elements
root.findall(".//") 给出:
[<Element '{http://www.w3.org/2000/svg}metadata' at 0x000001E19B2E5710>, <Element '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}RDF' at 0x000001E19B2E51C0>, <Element '{http://creativecommons.org/ns#}Work' at 0x000001E19B2E5670>, ...]
有了新元素列表,我想将其放回原始根格式,以便我可以将新根保存到 svg:
# Somehow get new_root = <Element '{http://www.w3.org/2000/svg}svg' at 0x000001E19B2E54E0>
ElementTree(new_root).write(svg)
svg.seek(0)
最后一部分将如何完成?谢谢
要操作 ElementTree 中的元素,然后将修改后的树保存回 SVG,可以按照以下步骤操作:
像这样:
import xml.etree.ElementTree as ET
from io import BytesIO
tree = ET.parse(svg)
root = tree.getroot()
# Namespace map to make finding elements easier
namespaces = {
'svg': 'http://www.w3.org/2000/svg',
# Add other namespaces here if necessary
}
# Iterate over all elements in the SVG
for elem in root.findall(".//svg:*", namespaces=namespaces):
# Manipulate elements here
print(elem.tag)
# Then write the tree back to the svg
svg.seek(0)
tree.write(svg, encoding='utf-8', xml_declaration=True)
# If you want to save to a file, you can do this instead:
with open("output.svg", "wb") as f:
tree.write(f, encoding='utf-8', xml_declaration=True)