xmlモジュール(了解)
3408 ワード
目次一、xml概要 二、Python使用xml 三、自分でxmlドキュメント を作成する
一、xmlの概要
xmlは異なる言語やプログラムの間でデータ交換を実現するプロトコルで、jsonとは差が少ないが、jsonの使用はもっと簡単だが、昔、jsonがまだ誕生していない暗い時代には、xmlを使うしかなかった.今まで多くの伝統的な会社、例えば金融業界の多くのシステムのインタフェースは主にxmlだった.
xmlのフォーマットは、<>ノードによってデータ構造を区別するものです.
二、Python xml使用
xmlプロトコルは各言語でサポートされており、pythonでは以下のモジュールでxmlを操作できます.
三、自分でxmlドキュメントを作成する
一、xmlの概要
xmlは異なる言語やプログラムの間でデータ交換を実現するプロトコルで、jsonとは差が少ないが、jsonの使用はもっと簡単だが、昔、jsonがまだ誕生していない暗い時代には、xmlを使うしかなかった.今まで多くの伝統的な会社、例えば金融業界の多くのシステムのインタフェースは主にxmlだった.
xmlのフォーマットは、<>ノードによってデータ構造を区別するものです.
2
2008
141100
5
2011
59900
69
2011
13600
二、Python xml使用
xmlプロトコルは各言語でサポートされており、pythonでは以下のモジュールでxmlを操作できます.
# print(root.iter('year')) #
# print(root.find('country')) # root ,
# print(root.findall('country')) # root ,
import xml.etree.ElementTree as ET
tree = ET.parse("xmltest.xml")
root = tree.getroot()
print(root.tag)
# xml
for child in root:
print('========>', child.tag, child.attrib, child.attrib['name'])
for i in child:
print(i.tag, i.attrib, i.text)
# year
for node in root.iter('year'):
print(node.tag, node.text)
#---------------------------------------
import xml.etree.ElementTree as ET
tree = ET.parse("xmltest.xml")
root = tree.getroot()
#
for node in root.iter('year'):
new_year = int(node.text) + 1
node.text = str(new_year)
node.set('updated', 'yes')
node.set('version', '1.0')
tree.write('test.xml')
# node
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country)
tree.write('output.xml')
# country (append) year2
import xml.etree.ElementTree as ET
tree = ET.parse("a.xml")
root = tree.getroot()
for country in root.findall('country'):
for year in country.findall('year'):
if int(year.text) > 2000:
year2 = ET.Element('year2')
year2.text = ' '
year2.attrib = {'update': 'yes'}
country.append(year2) # country
tree.write('a.xml.swap')
三、自分でxmlドキュメントを作成する
import xml.etree.ElementTree as ET
new_xml = ET.Element("namelist")
name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})
age = ET.SubElement(name, "age", attrib={"checked": "no"})
sex = ET.SubElement(name, "sex")
sex.text = '33'
name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
age = ET.SubElement(name2, "age")
age.text = '19'
et = ET.ElementTree(new_xml) #
et.write("test.xml", encoding="utf-8", xml_declaration=True)
ET.dump(new_xml) #