编辑:
这是我可以想到的lxml中最小的测试用例(完全用Python编写)
from lxml import etree
xslt_tree = etree.XML('''\
<?xml version="1.0" encoding="UTF-8"?>
<MD_Metadata xmlns="http://www.isotc211.org/2005/gmd" xmlns:gco="http://www.isotc211.org/2005/gco">
<language/>
<characterSet/>
</MD_Metadata>''')
doc = etree.XML('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:gmd="http://www.isotc211.org/2005/gmd" >
<!-- This adds the contact tag if it doesn't exist -->
<xsl:template match="/gmd:MD_Metadata">
<xsl:copy-of select="*"/>
<xsl:message>
Worked
</xsl:message>
</xsl:template>
</xsl:stylesheet>''')
transform = etree.XSLT(doc)
result = transform(xslt_tree)
print transform.error_log
print (etree.tostring(result,pretty_print=True))
这个输出
<language xmlns="http://www.isotc211.org/2005/gmd" xmlns:gco="http://www.isotc211.org/2005/gco"/>
什么时候应该输出
<MD_Metadata xmlns="http://www.isotc211.org/2005/gmd" xmlns:gco="http://www.isotc211.org/2005/gco">
<language/>
<characterSet/>
</MD_Metadata>
有什么想法吗?
旧问题
我有一个像这样的xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<MD_Metadata xmlns="http://www.isotc211.org/2005/gmd">
<language>
<LanguageCode codeList="http://www.loc.gov/standards/iso639-2/php/code_list.php" codeListValue="eng" codeSpace="ISO639-2">eng</LanguageCode>
</language>
<characterSet>
<MD_CharacterSetCode codeList="http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_CharacterSetCode" codeListValue="utf8" codeSpace="ISOTC211/19115">utf8</MD_CharacterSetCode>
</characterSet>
.... etc
</MD_Metadata>
和一个xlt文件,如下所示:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- Show all elements -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- This adds the contact tag if it doesn't exist -->
<xsl:template match="/gmd:MD_Metadata">
<xsl:copy-of select="@*|node()">
<xsl:if test="not(/gmd:MD_Metadata/gmd:contact)">
<xsl:element name="contact" namespace="http://www.isotc211.org/2005/gmd">
</xsl:element>
</xsl:if>
</xsl:copy-of>
</xsl:template>
</xsl:stylesheet>
当我在Python的lxml中运行它时,我得到了MD_Metadata元素并返回了第一个孩子。但是,当我使用默认的Java处理器或Xalan在Eclipse WTP(Eclipse XSL工具)中运行它时,我得到了MD_Metadata标记返回的所有元素,包括后来的characterSet和元素。对我来说,后者是标签带来的预期行为。我看不到在Python中调用转换时正在做的任何事情,但是以防万一:
xslt_root = lxml.etree.parse("XSLFile")
transform = lxml.etree.XSLT(xslt_root)
result_tree = transform(doc)
print (etree.tostring(result_tree,pretty_print=True))
我正在使用的两个处理器之间是否有实质性区别,还是有其他解释?
最佳答案
您得到奇怪行为的原因是xsl:copy-of
should be an empty element。我只能假定某些引擎正在“有帮助地”尝试以某种未定义的方式解释xsl:if
造成麻烦。
删除导致未定义行为的元素,并且应在不同引擎之间再次保持一致。
关于python - <copy-of> XLST标签未在不同处理器中一致地应用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19915933/