2015-07-21 47 views
0

在Python中,使用minidom,是否可以讀取/修改XML聲明?如何用minidom訪問XML聲明(python)

我有與

<?xml version="1.0" encoding='UTF-8' standalone='yes' ?> 

,我想對於例如啓動一個xml文件將其更改爲

<?xml-stylesheet href='form.xslt' type='text/xsl' ?> 

回答

1

您可以同時<?xml ?><?xml-stylesheet ?>(他們稱爲處理指令,順便說一句)在一個XML。要添加一個,只需創建ProcessingInstruction對象的實例和在根元素之前追加它,例如:

from xml.dom import minidom 

source = """<?xml version="1.0" ?> 
<root/>""" 
doc = minidom.parseString(source) 
pi = doc.createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="form.xslt"') 
doc.insertBefore(pi, doc.firstChild) 
print(doc.toprettyxml()) 

輸出:

<?xml version="1.0" ?> 
<?xml-stylesheet type="text/xsl" href="form.xslt"?> 
<root/>