我需要修改现有的xml文件。实际的文件看起来是这样的:修改现有的xml文件
<person id="1">
<address>Fr.</address>
<titles/>
<firstname>Mary</firstname>
<lastname>Müller</lastname>
<gender>F</gender>
<profession/>
<references>
<reference>
<positions>
<position>68-590-1</position>
<position>68-590-2</position>
</positions>
<positions>
<position>68-590-6</position>
<position>68-590-7</position>
</positions>
</reference>
</references>
</person>
我的问题是:我怎么能在这样的文件读取,然后添加信息。举例来说,如果这个人有行业“教授”,(这是在12-122-3位置写的),修改后的XML应该是这样的:
<person id="1">
<address>Fr.</address>
<titles/>
<firstname>Mary</firstname>
<lastname>Müller</lastname>
<gender>F</gender>
<profession>professor</profession>
<references>
<reference>
<positions>
<position>12-122-3</position>
</positions>
<positions>
<position>68-590-1</position>
<position>68-590-2</position>
</positions>
<positions>
<position>68-590-6</position>
<position>68-590-7</position>
</positions>
</reference>
</references>
</person>
感谢任何帮助! :)
什么我迄今所做的:
from xml.dom import minidom
doc = minidom.parse('SAC-Jahrbuch_1895_mul-ner.xml')
person = doc.getElementsByTagName('person')
lastnames = doc.getElementsByTagName('lastname')
positions = doc.getElementsByTagName('position')
professions = doc.getElementsByTagName('profession')
for ln in lastnames:
for pos in positions:
if ln.firstChild.nodeValue == u"Müller" and pos.firstChild.nodeValue == "68-590-2":
print "right person"
现在,我怎么能检查的人已经一个职业?如果不是的话:我该如何添加专业和职位? 非常感谢!
你有什么迄今所做?您是否尝试在Python教程中遵循至少一个XML? –
我用minidom试了一下。但它没有奏效。我会再试一次...... – MarkF6
从长远来看,您可能会想要使用['lxml'](http://lxml.de/)。你可以按照教程[这里](http://lxml.de/tutorial.html)。 – Midnighter