add element with attributes in minidom python

末鹿安然 提交于 2019-12-30 04:02:06

问题


I want to add a child node with attributes to a specific tag. my xml is

<deploy>
</deploy>

and the output should be

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

so far my code is:

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

How can I figure out how to find deploy tag and append child node with attributes ?


回答1:


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

Output file:

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


来源:https://stackoverflow.com/questions/17911674/add-element-with-attributes-in-minidom-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!