【发布时间】:2014-01-23 16:35:34
【问题描述】:
我有一个如下所示的 xml 文档:
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://someurl/Oldschema"
xsi:schemaLocation="http://someurl/Oldschema Oldschema.xsd"
xmlns:framework="http://someurl/Oldframework">
<framework:tag1> ... </framework:tag1>
<framework:tag2> <tagA> ... </tagA> </framwork:tag2>
</root>
我要做的就是将http://someurl/Oldschema 更改为http://someurl/Newschema 并将http://someurl/Oldframework 更改为http://someurl/Newframework 并保持其余文档不变。借助此线程lxml: add namespace to input file 的一些见解,我尝试了以下方法:
def fix_nsmap(nsmap, tag):
"""update the old nsmap-dict with the new schema-urls. Example:
fix_nsmap({"framework": "http://someurl/Oldframework",
None: "http://someurl/Oldschema"}) ==
{"framework": "http://someurl/Newframework",
None: "http://someurl/Newschema"}"""
...
from lxml import etree
root = etree.parse(XMLFILE).getroot()
root_tag = root.tag.split("}")[1]
nsmap = fix_nsmap(root.nsmap)
new_root = etree.Element(root_tag, nsmap=nsmap)
new_root[:] = root[:]
# ... fix xsi:schemaLocation
return etree.tostring(new_root, pretty_print=True, encoding="UTF-8",
xml_declaration=True)
这会在根标签中产生正确的“属性”,但对于文档的其余部分则完全失败:
<network xmlns:framework="http://someurl/Newframework"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://someurl/Newschema"
xsi:schemaLocation="http://someurl/Newschema Schema.xsd">
<ns0:tag1 xmlns:ns0="http://someurl/Oldframework"> ... </ns0:information>
<ns1:tag2 xmlns:ns1="http://someurl/Oldframework"
xmlns:ns2="http://someurl/Oldschema">
<ns2:tagA> ... </ns2:tagA>
</ns1:tag2>
我的方法有什么问题?有没有其他方法可以更改命名空间?也许我可以使用 xslt?
谢谢!
丹尼斯
【问题讨论】:
-
我的回答不是很受欢迎,所以我想补充一下:是的,我认为您可以使用 XSLT。见stackoverflow.com/a/31870245/407651 和stackoverflow.com/a/51660868/407651。