如何使用Python将名称空间和前缀插入XML字符串? [英] How to insert namespace and prefixes into an XML string with Python?
问题描述
假设我有一个XML字符串:
Suppose I have an XML string:
<A>
<B foo="123">
<C>thing</C>
<D>stuff</D>
</B>
</A>
并且我想插入XML Schema使用的类型的名称空间,在所有元素名称的前面放置一个前缀.
and I want to insert a namespace of the type used by XML Schema, putting a prefix in front of all the element names.
<A xmlns:ns1="www.example.com">
<ns1:B foo="123">
<ns1:C>thing</ns1:C>
<ns1:D>stuff</ns1:D>
</ns1:B>
</A>
是否可以使用lxml.etree
或类似的库来执行此操作(除了蛮力查找替换或正则表达式)?
Is there a way to do this (aside from brute-force find-replace or regex) using lxml.etree
or a similar library?
推荐答案
我认为仅ElementTree不能做到这一点.
I don't think this can be done with just ElementTree.
操纵名称空间有时会非常棘手.关于SO,这里有很多问题.即使使用更高级的 lxml 库,也确实很难.请参阅以下相关问题:
Manipulating namespaces is sometimes surprisingly tricky. There are many questions about it here on SO. Even with the more advanced lxml library, it can be really hard. See these related questions:
- lxml: add namespace to input file
- Modify namespaces in a given xml document with lxml
- lxml etree xmlparser remove unwanted namespace
下面是使用XSLT的解决方案.
Below is a solution that uses XSLT.
代码:
from lxml import etree
XML = '''
<A>
<B foo="123">
<C>thing</C>
<D>stuff</D>
</B>
</A>'''
XSLT = '''
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ns1="www.example.com">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:template match="*">
<xsl:element name="ns1:{name()}">
<xsl:apply-templates select="node()|@*"/>
</xsl:element>
</xsl:template>
<!-- No prefix on the A element -->
<xsl:template match="A">
<A xmlns:ns1="www.example.com">
<xsl:apply-templates select="node()|@*"/>
</A>
</xsl:template>
</xsl:stylesheet>'''
xml_doc = etree.fromstring(XML)
xslt_doc = etree.fromstring(XSLT)
transform = etree.XSLT(xslt_doc)
print transform(xml_doc)
输出:
<A xmlns:ns1="www.example.com">
<ns1:B foo="123">
<ns1:C>thing</ns1:C>
<ns1:D>stuff</ns1:D>
</ns1:B>
</A>
这篇关于如何使用Python将名称空间和前缀插入XML字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!