[python] append child v xml...

Luc@sh lukas na pleva.cz
Pátek Březen 31 13:26:26 CEST 2017


Nejdriv vsem diky za rady...a mam dalsi otazku:

reseni: mam xml soubor a chci do nej pridat element(additionalData)...tak  
aby byl pridan do kazdeho "data"

Kdyz mam xml soubor, ktery obsahuje(zkraceno)(vzor1.xml):
<neco>
	<tagA>Ahoj Svete</tagA>
</neco>
<data>
	<host>localhost</host>
	<user>root</user>
</data>

potom mam program:

 from xml.dom import minidom
def findTextNodes(nodeList, tagname, new):
	for subnode in nodeList:
		if subnode.nodeType == subnode.ELEMENT_NODE:
			if (subnode.nodeType == subnode.ELEMENT_NODE and subnode.tagName ==  
tagname):
				new = doc.createElement(new)
				subnode.appendChild(new)
				new.appendChild(doc.createTextNode("tento text doplnen"))
			findTextNodes(subnode.childNodes, tagname, new)

doc = minidom.parse('vzor1.xml')
findTextNodes(doc.childNodes, "data", "AdditionalData")
print doc.toxml()


A vsechno funguje bez problemu... sice mi to tam prida podivne(ze neudela  
ten tabulator a na konci prechod na dalsi radek)
vysledek:
<neco>
	<tagA>Ahoj Svete</tagA>
</neco>
<data>
	<host>localhost</host>
	<user>root</user>
<AdditionalData>tento text doplnen</AdditionalData></data>



ALE kdyz zmenim XML na:
<neco>
	<tagA>Ahoj Svete</tagA>
</neco>
<data>
	<host>localhost</host>
	<user>root</user>
</data>
<data>
	<host>local</host>
	<user>toor</user>
</data>

tak uz pridavani nefunguje a hodi to opravdu zvlastni chybu:

Traceback (most recent call last):
   File "together1.py", line 26, in ?
     print doc.toxml()
   File "/home/pleva/lib/_xmlplus/dom/minidom.py", line 47, in toxml
     return self.toprettyxml("", "", encoding)
   File "/home/pleva/lib/_xmlplus/dom/minidom.py", line 59, in toprettyxml
     self.writexml(writer, "", indent, newl, encoding)
   File "/home/pleva/lib/_xmlplus/dom/minidom.py", line 1746, in writexml
     node.writexml(writer, indent, addindent, newl)
   File "/home/pleva/lib/_xmlplus/dom/minidom.py", line 821, in writexml
     node.writexml(writer,indent+addindent,addindent,newl)
   File "/home/pleva/lib/_xmlplus/dom/minidom.py", line 821, in writexml
     node.writexml(writer,indent+addindent,addindent,newl)
   File "/home/pleva/lib/_xmlplus/dom/minidom.py", line 808, in writexml
     writer.write(indent+"<" + self.tagName)
TypeError: cannot concatenate 'str' and 'instance' objects

-z cehoz jsem pochopil, ze nemuze spojit tag, ale vubec nevim kvuli cemu...

Tak predem moc dik za rady, uz to vidim, ze to bude zas naka banalita :))

Lukas


Další informace o konferenci Python