2013-07-28 15 views
11

属性を持つ子ノードを特定のタグに追加します。私のXMLはminidom pythonの属性を持つ要素を追加してください

<deploy> 
</deploy> 

で、出力はこれまでのところ私のコードがある

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

する必要があります:私は展開し、タグを見つけるとして子ノードを追加する方法を見つけ出すことができますどのように

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

属性?

答えて

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() 

出力ファイル:

<?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

これに答えるためのおかげでウィリアムはquestion.reallyフル助けます –

関連する問題