0

我有一个带有<en-media>标签的 XML 文档:

<en-media type="image/png" hash="06c5ec15535babbcd3eef471f51af870"/>

我正在尝试将该标签更改为 HTML <img>,使其如下所示:

<img src="06c5ec15535babbcd3eef471f51af870"/>

这是因为文件以其哈希命名。

我一直在使用 xml.etree.ElementTree 来尝试这样做,并且我一直在查看http://docs.python.org/2/library/xml.etree.elementtree.html但我似乎无法获得任何工作.

谁能帮我这个?

谢谢

4

2 回答 2

1

这是如何使用 ElementTree 完成的。

输入 XML (test.xml):

<root>
  <en-media type="image/png" hash="06c5ec15535babbcd3eef471f51af870"/>
</root>

Python代码:

from xml.etree import ElementTree as ET

root = ET.parse("test.xml").getroot()

# Get the 'en_media' element
en_media = root.find("en-media")

# Add the 'img' element (with 'src' attribute) as a sub-element of 'root'
img = ET.SubElement(root, "img", src=en_media.get("hash"))

# Remove 'en_media'
root.remove(en_media)

print ET.tostring(root)

输出:

<root>
  <img src="06c5ec15535babbcd3eef471f51af870" /></root>
于 2013-11-14T17:54:35.847 回答
0

您可以使用BeautifulSoup

例如:

from bs4 import BeautifulSoup
a = BeautifulSoup("<somelink rel='stylesheet'>")
print a
# output : <html><body><somelink rel="stylesheet"></somelink></body></html>
b = a.somelink
b.name = "link"
print a
# output : <html><body><link rel="stylesheet"></link></body></html>
print b
# output : <link rel="stylesheet"></link>
于 2013-11-10T10:08:23.097 回答