gpt4 book ai didi

python - 如何向在Python中使用lxml中的xpath找到的标签添加属性?

转载 作者:太空宇宙 更新时间:2023-11-03 16:29:34 25 4
gpt4 key购买 nike

我有以下 xml -

<draw:image></draw:image>

我想给它添加多个xlink属性并使其 -

<draw:image xlink:href="image" xlink:show="embed"></draw:image>

我尝试使用以下代码,但收到错误“ValueError: Invalid attribute name u'xlink:href'”

root.xpath("//draw:image", namespaces=
{"draw":"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"})
[0].attrib['xlink:href'] = 'image'

我做错了什么?似乎有一些与命名空间相关的东西,但我不知道是什么。

最佳答案

这是一个工作示例:

from lxml import etree as et

xml = et.parse("your.xml")
root = xml.getroot()
d = root.nsmap

for node in root.xpath("//draw:image", namespaces=d):
node.attrib["{http://www.w3.org/1999/xlink}href"] = "value"
node.attrib["{http://www.w3.org/1999/xlink}show"] = "embed"
print(et.tostring(xml))

用于:

<?xml version="1.0" encoding="utf-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"
xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"
xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"
xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0"
xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0"
xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"
xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0"
xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0">
<draw:image></draw:image>

输出:

<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0">
<draw:image xlink:href="value" xlink:show="embed"/>


</office:document>

或者使用集合:

for node in root.xpath("//draw:image", namespaces=d):
node.set("{http://www.w3.org/1999/xlink}href", "image")
node.set("{http://www.w3.org/1999/xlink}show", "embed")

关于python - 如何向在Python中使用lxml中的xpath找到的标签添加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37714813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com