在minidom python中添加具有属性的元素

2024-05-14 06:10:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将具有属性的子节点添加到特定标记。我的xml是

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

如何找到deploy标记并附加具有属性的子节点?


Tags: 代码name标记属性节点parsescriptaction
1条回答
网友
1楼 · 发布于 2024-05-14 06:10:39

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>

相关问题 更多 >