[英]adding nodes to xml file with same node name but different attributes with Python Dom
is it possible to add two nodes with the same name to a xml document ? 是否可以将两个具有相同名称的节点添加到xml文档中?
That is something like that : 那是这样的:
Initial file : 初始文件:
<Files>
<Filter>
</Filter>
</Files>
Wanted file : 想要的文件:
<Files>
<Filter>
<File RelativePath=".\src\aaa.cxx" ></File>
<File RelativePath=".\src\bbb.cxx"></File>
</Filter>
</Files>
I would like to do that with Python, dom or minidom. 我想用Python,dom或minidom做到这一点。
I tried to use the appendChild function but if only keep one node of the same name. 我尝试使用appendChild函数,但是如果只保留一个同名节点。
I tried to use the insertBefore function but it doesn't seem to work also. 我尝试使用insertBefore函数,但它似乎也不起作用。
Here is the source code I used with insertBefore (with appendChild, just have to remove the nbOfFiles control) : 这是我与insertBefore一起使用的源代码(与appendChild一起使用,只需删除nbOfFiles控件):
document = xml.dom.minidom.parse (fileTmp)
filesItem = Item.getElementsByTagName("Files")[0]
for filter in filesItem.getElementsByTagName("Filter") :
filterAttribute = filter.getAttribute("Filter")
filePath = os.path.split (fileTmp)[0] + "/src"
filesInPath = os.listdir (filePath)
fileElement = document.createElement ("File")
nbOfFiles = 0
for file in filesInPath :
fileElement.setAttribute ("RelativePath", file)
if nbOfFiles == 0 :
filter.appendChild (fileElement)
lastFileElement = fileElement
nbOfFiles = nbOfFiles + 1
else :
filter.insertBefore (fileElement, None)
Thanks for your help. 谢谢你的帮助。
Not sure where your code is going wrong, as you've not provided a testable example. 由于您没有提供可测试的示例,因此不确定代码在哪里出错。 I'm not particularly familiar with minidom, I prefer lxml. 我对minidom并不是特别熟悉,我更喜欢lxml。
I suspect you need to instantiate each new child node separately. 我怀疑您需要分别实例化每个新的子节点。
This works for me: 这对我有用:
>>> import xml.dom.minidom
>>>
>>> data_in = """<Files>
... <Filter>
... </Filter>
... </Files>
... """
>>>
>>> data_add = ('./src/aaa.cxx','./src/bbb.cxx')
>>>
>>> doc = xml.dom.minidom.parseString(data_in)
>>> files= doc.getElementsByTagName("Files")[0]
>>> for filter in files.getElementsByTagName("Filter"):
... for item in data_add:
... newNode = doc.createElement("File")
... newNode.setAttribute('RelativePath',item)
... filter.appendChild(newNode)
...
<DOM Element: File at 0x984c66c>
<DOM Element: File at 0x984c80c>
>>> print doc.toxml()
<?xml version="1.0" ?>
<Files>
<Filter>
<File RelativePath="./src/aaa.cxx"/><File RelativePath="./src/bbb.cxx"/></Filter>
</Files>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.