gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:29:41 24 4
gpt4 key购买 nike

我想为特定标签添加一个带有属性的子节点。我的 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)

我怎样才能弄清楚如何找到部署标签并附加带有属性的子节点?

最佳答案

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>

关于python - 在minidom python中添加具有属性的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17911674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com