Ven*_*esh 2 javascript python xml lxml xml-parsing
我有一个带有javascript的XSLT,它使用"<" 和">" 在里面循环
<?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>
Run Code Online (Sandbox Code Playgroud)
我正在使用PYTHON LXML库使用XSLT和XML生成HTML.
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()
Run Code Online (Sandbox Code Playgroud)
但是LXML无法替换输出HTML文件中的特殊字符
< 到'<'和> 到'>'
是否有任何使用LXML替换"<"的标准做法 到'<'?
为了解决这个问题,我必须在写入文件之前编写另一段代码.
content = content.replace(">", ">")
content = content.replace("<", "<")
Run Code Online (Sandbox Code Playgroud)
为了解码/转换HTML实体,您应该method="html"在tostring()调用中使用:
ET.tostring(content, method="html", pretty_print=True)
Run Code Online (Sandbox Code Playgroud)
要么:
lxml.html.tostring(content, pretty_print=True)
Run Code Online (Sandbox Code Playgroud)
DEMO:
from lxml import etree
text = """<html>
<body>
<script> 1 < 2 </script>
</body>
</html>
"""
tree = etree.fromstring(text)
print etree.tostring(tree, method="html")
Run Code Online (Sandbox Code Playgroud)
打印:
<html>
<body>
<script> 1 < 2 </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2958 次 |
| 最近记录: |