使用minidom创建XML文件

2024-10-03 21:31:29 发布

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

我想用python创建一个xml文件,格式如下:

<datasource formatted-name='federated' inline='true'>
  <connection class='federated'>
    <named-connections>
      <named-connection caption='Sample - Superstore' name='excel.1ew9u4t0tggb9315darmm0nfz2kb'>
        <connection class='excel' driver='' header='yes' imex='1' password='' server='' />
      </named-connection>
    </named-connections>
  </connection>
</datasource>

我试过用minidom

from xml.dom import minidom 
import os  

root = minidom.Document() 
  
xml = root.createElement('Datasource')  
root.appendChild(xml) 
  
productChild = root.createElement('Connection') 
productChild.setAttribute('name', 'Federated') 
xml.appendChild(productChild) 

productChild1 = root.createTextNode('named-connections') 
productChild2=root.createElement('named-connection')
productChild2.setAttribute('name', 'caption=SampleSuperstore')
xml.appendChild(productChild1)
  
xml_str = root.toprettyxml(indent ="\t")  
  
save_path_file = "gfg.xml"
  
with open(save_path_file, "w") as f: 
    f.write(xml_str)

我只得到这个

<?xml version="1.0" ?>
<Database>
    <Connection name="Federated"/>
    named-connections
</Database>

我不知道如何在<named-connections>内创建子节点。有人能帮忙吗

谢谢, 阿鲁什


Tags: nameimportrootxmlconnectionconnectionsclassnamed
1条回答
网友
1楼 · 发布于 2024-10-03 21:31:29

我也在找同样的东西。我一直在寻找答案。如果其他人需要相同的信息:

root = minidom.Document() 
 
xml = root.createElement('Datasource')  
root.appendChild(xml) 

productChild = root.createElement('connection')
productChild.setAttribute('formatted-name', 'Federated') 
productChild.setAttribute('inline', 'true') 
xml.appendChild(productChild)

# named-connections indent
childOfProduct = root.createElement('named-connections')
productChild.appendChild(childOfProduct)

# named-connection indent
productChild1 = root.createElement('named-connection')
productChild1.setAttribute('caption', 'Sample - Superstore')
productChild1.setAttribute('name', 'excel.1ew9u4t0tggb9315darmm0nfz2kb')
childOfProduct.appendChild(productChild1)

# connection indent
productChild2 = root.createElement('connection')
productChild2.setAttribute('class', 'excel')
productChild2.setAttribute('driver', '')
productChild2.setAttribute('header', 'yes')
productChild2.setAttribute('imex', '1')
productChild2.setAttribute('password', '')
productChild2.setAttribute('server', '')
productChild1.appendChild(productChild2)


对不起,如果有什么不对劲,我不是专业人士。 希望这对未来的搜索者有所帮助

相关问题 更多 >