python修改远程linux机器xml标签的值
转载
tree.write(xml_file) #将修改写入本地xml文件def prettyXml(element, indent, newline, level = 0): # elemnt为传进来的Elment类,参数indent用于缩进,newline用于换行
if element: # 判断element是否有子元素
if element.text == None or element.text.isspace(): # 如果element的text没有内容
element.text = newline + indent * (level + 1)
else:
element.text = newline + indent * (level + 1) + element.text.strip() + newline + indent * (level + 1)
#else: # 此处两行如果把注释去掉,Element的text也会另起一行
#element.text = newline + indent * (level + 1) + element.text.strip() + newline + indent * level
temp = list(element) # 将elemnt转成list
for subelement in temp:
if temp.index(subelement) < (len(temp) - 1): # 如果不是list的最后一个元素,说明下一个行是同级别元素的起始,缩进应一致
subelement.tail = newline + indent * (level + 1)
else: # 如果是list的最后一个元素, 说明下一行是母元素的结束,缩进应该少一个
subelement.tail = newline + indent * level
prettyXml(subelement, indent, newline, level = level + 1) # 对子元素进行递归操作xml_file = ‘/tmp/template.xml’
create_Xml(xml_file)## 2 查看并修改xml文件内容
**查看所有的neighbor信息,并把attrib属性中’direction’为‘E’的修改为‘East’**for neighbor in root.iter(‘neighbor’):
… if neighbor.attrib[‘direction’] == ‘E’:
… neighbor.attrib[‘direction’] = ‘East’
… print(neighbor.attrib)
…
{‘direction’: ‘East’, ‘name’: ‘Austria’}
{‘direction’: ‘W’, ‘name’: ‘Switzerland’}
{‘direction’: ‘N’, ‘name’: ‘Malaysia’}
{‘direction’: ‘W’, ‘name’: ‘Costa Rica’}
{‘direction’: ‘East’, ‘name’: ‘Colombia’}**获取country name和rank属性**for country in root.findall(‘country’):
… rank = country.find(‘rank’).text
… name = country.get(‘name’)
… print(name, rank)
…
Liechtenstein 1
Singapore 4
Panama 68**在rank标签中新增attrib属性**for rank in root.iter(‘rank’):
… new_rank = int(rank.text) + 1
… rank.text = str(new_rank)
… rank.set(‘updated’, ‘yes’)
…
tree.write(‘/tmp/output.xml’)修改后的xml文件如下: false 2 2008 141100 5 2011 59900 69 2011 13600
## 3 删除xml文件内容
**删除rank > 3的country,删除builders下的hudson.tasks.Shell标签,并配置text为deleted**for country in root.findall(‘country’):
… rank = int(country.find(‘rank’).text)
… if rank > 3:
… root.remove(country)
…
for builders in root.findall(‘builders’):
… for shell in builders.findall(‘hudson.tasks.Shell’):
… builders.remove(shell)
… builders.text = ‘deleted’
…
tree.write(‘/tmp/output.xml’)修改后的xml文件: false 2 2008 141100 deleted
当一个页签下面有多个子标签时使用remove删除发现一次删不全
比如下面文件<hudson.model.ListView>
test_all
compile
get_node_list
job_data
new_job
pipeline0
pipeline1
template
test_1
test_2
test_3
false
</hudson.model.ListView>想删除jobNames标签下的所有string标签,可先获取string的数量num然后执行num次删除操作,删除部分代码参考如下root = tree.getroot()
for i in range(0,self.num):
for jobNames in root.findall(‘jobNames’):
for string in jobNames:
if string.text:
jobNames.remove(string)
本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。