-
python自带的xml库
-
第三方库 lxml
xml库(xml.etree.ElementTree)formstring专属
import xml.etree.ElementTree as Et #导入库,起别名
xml_content = """
<root>
<a>
<b>hello</b>
<c>world</c>
</a>
</root>
"""
root = ET.fromstring(xml_content)
print(root)
print(root.tag) #打印出它的标记名
print(root.attrib) #获取他的属性,就是tag里面的值
# 可以迭代父节点
for i in root:
print(i.tag,i.attrib)
# 通过下标取元素
print(root[0][1].text)
# 遍历某个节点下所有节点的tag和attribe
for i in root.iter('definition'):
print(i.tag,i.attribe)
# 类似bs4查找元素,只能找当前的节点下的一层,第二层不能找到。
for i in root.findall('tagName'):
print(i.tag,i.attribe)
xml库(xml.etree.ElementTree)(通过文件来修改内容,)
import xml.etree.ElementTree as ET
if __name__ == '__main__':
# 获得树结构
tree = ET.parse('jenkins_mould/config2.xml')
#获得根结构
root = tree.getroot()
#修改xml文件
# for rank in root.iter('description'):
# new = int(rank.text) + 1
# rank.text = str(new)
# 删除xml文件
for i in root.findall('description'):
rank = i.find('rank').text
root.remove(i)
tree.write('jenkins_mould/config2.xml')
import xml.etree.ElementTree as ET
#自己写个xml
if __name__ == '__main__':
a=ET.Element('root')
b=ET.SubElement(a,'child',attrib={'class':'aoligei'})
c=ET.SubElement(b,'sunzi',attrib={'id':'diyi'})
ET.dump(a)