我想保留 xml 样式表。但这不起作用。 我使用Python修改XML以自动部署hadoop。
XML:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<!-- Put site-specific property overrides in this file. -->
<configuration>
<property>
<name>fs.default.name</name>
<value>hdfs://c11:9000</value>
</property>
</configuration>
代码:
from xml.etree.ElementTree import ElementTree as ET
def modify_core_site(namenode_hostname):
tree = ET()
tree.parse("pkg/core-site.xml")
root = tree.getroot()
for p in root.iter("property"):
name = p.find("name").text
if name == "fs.default.name":
text = "hdfs://%s:9000" % namenode_hostname
p.find("value").text = text
tree.write("pkg/tmp.xml", encoding="utf-8", xml_declaration=True)
modify_core_site("c80")
结果:
<?xml version='1.0' encoding='utf-8'?>
<configuration>
<property>
<name>fs.default.name</name>
<value>hdfs://c80:9000</value>
</property>
</configuration>
xml 样式表消失... 我怎样才能保留这个?
最佳答案
一种解决方案是您可以使用 lxml解析 xml 后,直到找到 xsl 节点。下面是快速示例:
>>> import lxml.etree
>>> doc = lxml.etree.parse('C:/downloads/xmltest.xml')
>>> root = doc.getroot()
>>> xslnode=root.getprevious().getprevious()
>>> xslnode
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
确保进行一些异常处理并检查节点是否确实存在。您可以通过以下方式检查节点是否是xslt处理指令
>>> isinstance(xslnode, lxml.etree._XSLTProcessingInstruction)
True
关于python - 如何保留 xml 样式表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26442708/