2016-06-08 36 views
1

我有以下XML -如何在Python中使用lxml中的xpath找到的標籤添加屬性?

<draw:image></draw:image> 

我想多XLink屬性添加到它,讓它 -

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

我嘗試使用下面的代碼,但得到的錯誤「ValueError異常:無效的屬性名字u'xlink:href'「

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

我在做什麼錯?似乎有一些與命名空間有關的東西,但我無法弄清楚什麼。

+0

你可以添加一個鏈接到實際的文件?或者至少有一個與名稱空間decs等可用的版本,.. –

+0

@PadraicCunningham啊。好的。這裏是命名空間 - https://gist.github.com/shrox/df592e65a8848dd4f0ddab18cc340dd4 –

+0

你能添加一個淡化版本的文件嗎?向你展示一個完整的例子會更容易。 –

回答

1

這是一個工作示例:

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> 

或者使用set:

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") 
+0

你不知道你一直很有幫助。自從昨天以來,我一直很難理解名稱空間是如何工作的,這已經爲我簡化了它。謝謝! –

相關問題