2013-07-28 4 views
11

Ich möchte einen untergeordneten Knoten mit Attributen zu einem bestimmten Tag hinzufügen. mein xml istElement mit Attributen in minidom python hinzufügen

<deploy> 
</deploy> 

und der Ausgang

<deploy> 
    <script name="xyz" action="stop"/> 
</deploy> 

bisher mein Code sein sollte:

dom = parse("deploy.xml") 
script = dom.createElement("script") 
dom.childNodes[0].appendChild(script) 
dom.writexml(open(weblogicDeployXML, 'w')) 
script.setAttribute("name", args.script) 

Wie kann ich Tag bereitstellen, herauszufinden, wie zu finden und Knoten anhängen Kind mit Attribute?

Antwort

13

xml.dom.Element.setAttribute

xmlFile = minidom.parse(FILE_PATH) 

for script in SCRIPTS: 

    newScript = xmlFile.createElement("script") 

    newScript.setAttribute("name" , script.name) 
    newScript.setAttribute("action", script.action) 

    newScriptText = xmlFile.createTextNode(script.description) 

    newScript.appendChild(newScriptText ) 
    xmlFile.childNodes[0].appendChild(newScript) 

print xmlFile.toprettyxml() 

Ausgabedatei:

<?xml version="1.0" ?> 
<scripts> 
    <script action="list" name="ls" > List a directory </script> 
    <script action="copy" name="cp" > Copy a file/directory </script> 
    <script action="move" name="mv" > Move a file/directory </script> 
    . 
    . 
    . 
</scripts> 
+0

dank William für die Beantwortung dieser question.really voll helfen –