问题
I have an XSLT with javascript in it which uses "< ;" and "> ;" inside for loop
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head> </head>
<body>
<script language="javascript" type="text/javascript">
function example() {
var trs = document.getElementsByTagName("tr");
for (var i = 0; i < trs.length; i++) {
}
}
</script>
</body>
</html>
I am using PYTHON LXML library to generate HTML using XSLT and XML.
import lxml.etree as ET
xml = ET.parse('sample.xml')
xslt = ET.parse('sample.xsl')
transform = ET.XSLT(xslt)
content = transform(xml)
f = open('output.html','w')
f.write(ET.tostring(content , pretty_print=True))
f.close()
But LXML is unable to replace special characters in the output HTML file
< ; to '<' and > ; to '>'
Is there any standard practice using LXML to replace "< ;" to '<' ?
To over come this issue I have to write another piece of code before writing to the file.
content = content.replace(">", ">")
content = content.replace("<", "<")
回答1:
In order to decode/convert HTML entities, you should use method="html"
in tostring()
call:
ET.tostring(content, method="html", pretty_print=True)
or:
lxml.html.tostring(content, pretty_print=True)
DEMO:
from lxml import etree
text = """<html>
<body>
<script> 1 < 2 </script>
</body>
</html>
"""
tree = etree.fromstring(text)
print etree.tostring(tree, method="html")
prints:
<html>
<body>
<script> 1 < 2 </script>
</body>
</html>
回答2:
You can also just surround the script contents in a CDATA wrapper to stop it getting eaten, like so:
<script language="javascript" type="text/javascript">
<![CDATA[
function example() {
var trs = document.getElementsByTagName("tr");
for (var i = 0; i < trs.length; i++) {
}
}
]]>
</script>
来源:https://stackoverflow.com/questions/19017253/python-lxml-library-fails-to-parse-lt-and-gt