简体   繁体   中英

How to use custom xml tags in xslt with python lxml module

I am trying to create an xslt file that contains some tags that I want to use internally for my own purposes but that won't break the xslt transform parser.

As an example, given this xslt file:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<my_super_tag>
some great value
</my_super_tag>
<xsl:template match="/">
  <html>
  <body>
Hello World
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

I can get the behaviour I want if I do the following in python 2.7:

import lxml.etree as ET
dom = ET.fromstring(XML_string)
xslt = ET.fromstring(XSLT_string)
for my_tag in xslt.xpath("//my_super_tag"):
    #  do something wonderful with my_tag
    my_tag.getparent().remove(my_tag)
transform = ET.XSLT(xslt)
newdom = transform(dom)

So, what I am doing is preparsing the xslt file to get my tags, and removing them before I actually try to create the transform. I have to believe I am doing something over complicated here and that there is a better way to set up my xslt so that is contains the tags and content I want, but is still a valid xslt (and does not place my special tags in the output of the transform), so that the output of the transform is:

  <html>
  <body>
Hello World
  </body>
  </html>

Is there a better, more standard, way to do this?

Top level elements need to be put in a different namespace eg

<my_super_tag xmlns="http://example.com/">
some great value
</my_super_tag>

see http://www.w3.org/TR/xslt#stylesheet-element , which says:

In addition, the xsl:stylesheet element may contain any element not from the XSLT namespace, provided that the expanded-name of the element has a non-null namespace URI. The presence of such top-level elements must not change the behavior of XSLT elements and functions defined in this document; for example, it would not be permitted for such a top-level element to specify that xsl:apply-templates was to use different rules to resolve conflicts. Thus, an XSLT processor is always free to ignore such top-level elements, and must ignore a top-level element without giving an error if it does not recognize the namespace URI.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM