简体   繁体   English

使用xml.dom.minidom python将attibute和值添加到xml

[英]Adding an attibute and value to an xml using xml.dom.minidom python

How can I add an attribut and value to an XML document using xml.dom.minidom in Python. 如何在Python中使用xml.dom.minidom向XML文档添加属性和值。

My XML is as follows 我的XML如下

<?xml version="1.0" encoding="utf-8"?>

<PackageInfo xmlns="http://someurlpackage">


<data ID="http://someurldata1">data1</data >
<data ID="http://someurldata2">data2</data >
<data ID="http://someurldata3">data3</data >
</PackageInfo>

I want to add a new 'data' tag and it's id as ' http://someurldata4 ' and value as data4. 我想添加一个新的“数据”标记,其ID为“ http:// someurldata4 ”,值作为data4。 So that the resulting xml will be as below. 这样生成的xml将如下所示。 Sorry I don't want to use xml.etree.ElementTree 抱歉,我不想使用xml.etree.ElementTree

<?xml version="1.0" encoding="utf-8"?>

<PackageInfo xmlns="http://someurlpackage">
<data ID="http://someurldata1">data1</data >
<data ID="http://someurldata2">data2</data >
<data ID="http://someurldata3">data3</data >
<data ID="http://someurldata4">data4</data >
</PackageInfo>

You create new DOM elements with the Document.createElement() method , new DOM attributes can be added with the Element.setAttribute() method : 使用Document.createElement()方法创建新的DOM元素,可以使用Element.setAttribute()方法添加新的DOM属性:

newdata = doc.createElement(u'data')
newdata.setAttribute(u'ID', u'http://someurldata4')

You then have to create a text node and add that as a child to the newdata Element, using the Document.createTextNode() and Node.appendChild() methods: 然后,您必须使用Document.createTextNode()Node.appendChild()方法创建一个文本节点并将其作为子元素添加到newdata元素中:

newdata.appendChild(doc.createTextNode(u'data4'))

Now you can add the new element to your document root: 现在,您可以将新元素添加到文档根目录:

doc.documentElement.appendChild(newdata)

In other words, use the Python implementation of the DOM API . 换句话说,使用DOM APIPython实现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM