2 回答
TA贡献1815条经验 获得超6个赞
from lxml import etree
root = etree.parse(r'<your file.xml>')
for name in root.xpath('//name[./following-sibling::displayName]'):
name.getnext().text = name.text
print( etree.tostring(root, pretty_print=True).decode('utf-8') )
印刷:
<component xmlns:xsi="http://www.w3.orgr">
<memoryMaps>
<memoryMap>
<name>name</name>
<description>description</description>
<peripheral>
<name>periph</name>
<description>description</description>
<baseAddress>0x0</baseAddress>
<range>0x8</range>
<width>32</width>
<registers>
<register>
<name>reg1</name>
<displayName>reg1</displayName>
....
</register>
<register>
<name>reg2</name>
<displayName>reg2</displayName>
.................
</register>
<register>
<name>reg3</name>
<displayName>reg3</displayName>
..................
</register>
</registers>
</peripheral>
</memoryMap>
</memoryMaps>
</component>
TA贡献1848条经验 获得超10个赞
推荐你一个简单的库。
from simplified_scrapy import SimplifiedDoc, utils
# xml = utils.getFileContent('your xml path')
xml = '''
<registers>
<register>
<name>reg1</name>
<displayName>1</displayName>
....
</register>
<register>
<name>reg2</name>
<displayName>1</displayName>
.................
</register>
<register>
<name>reg3</name>
<displayName>1</displayName>
..................
</register>
</registers>
'''
doc = SimplifiedDoc(xml) # create doc
registers = doc.selects('register')
for r in registers:
r.displayName.setContent(r.name.html)
# Or
names = doc.selects('register>name')
for n in names:
n.setContent(n.next.html)
# Or
# n.setContent(n.getNext('displayName').html)
print(doc.html)
结果:
<registers>
<register>
<name>reg1</name>
<displayName>reg1</displayName>
....
</register>
<register>
<name>reg2</name>
<displayName>reg2</displayName>
.................
</register>
<register>
<name>reg3</name>
<displayName>reg3</displayName>
..................
</register>
</registers>
添加回答
举报