xml(Extensible Markup Language,简称:XML)
Extensible Markup Language はnetconf
構成ファイル形式です。これは本質的に階層的なデータ形式であり、最も自然な表現はそれをツリーに解析することです。ただし、xml
そのようなラベル データは「機械」の認識を対象としており、「人間」の認識には役に立たないので、もっと面倒なようです。
Netconf
ワーキング グループは 2003 年 5 月に設立されました。このワーキング グループは主に、新しい XML ベースのネットワーク構成 (NETCONF
) プロトコルを提案することを目的としています。設立。
Python
組み込み API:xml.etree.ElementTree
ファイルを解析できますxml
。 ドキュメント全体をツリー構造に解析します。 はこのツリー構造内の単一のノードを表します。 ElementTree
xml
Element
官方文件地址:The ElementTree XML API
次の例は、次の xml ファイルの形式になっており、これも公式のケースです。 xml
ドキュメントの例は次のとおりです。
xml
文書の例は次のとおりです。
<?xml version="1.0"?>
<data id="world country">
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
1. XMLデータ形式
Element
共通属性に対応する形式xml
は次のとおりです:
<tag attrib=“netmiko_inventory”>text</tag>
例:
<device_type desc="platform">cisco_ios</device_type>
tag attrib text tag
で:
1、 tag
: XML タグを表す str オブジェクトです。この例では、前後で閉じられています。device_type
2. < /span> タグ、以下に示すように、 : タグのペアに含まれるサブセットです 4、 コンテンツ、例では : これは、 XML データ タグ、 3 の xml 属性を表す dict オブジェクトです。 attrib
: これは、例 desc="platform"
text
Element
cisco_ios
child elements
xml
country
例:
import xml.etree.ElementTree as ET
# 读取、解析文件,获取跟元素
tree = ET.parse('sample.xml')
root = tree.getroot()
# 获取根元素的标签名称以及所有属性
# data
print('root.tag:', root.tag)
print('root.attrib:', root.attrib)
# 获取text
print(root[0][1].text)
出力結果:
root.tag: data
root.attrib: {'id': 'world country'}
2008
2. 検索方法
Element
検索方法はたくさんありますが、まとめると次のようになります。
iter(tag=None)
: 遍历Element
的child
,可以指定tag
精确查找;findall(match)
: 現在の要素tag
またはpath
と一致するchild
ノードを検索します。find(match)
: 現在の要素tag
またはpath
が一致する最初のchild
ノードを検索します。get(key, default=None)
:获取元素指定key
对应的attrib
,如果没有attrib
,返回default
。
# 一次性获取所有名为 country 的元素、然后遍历
for country in root.findall('country'):
# 获取 country 元素中的 name 属性
name = country.get('name')
# 寻找名为 rank 的子节点,获取其text
rank = country.find('rank').text
# 一次性获取所有名为 country 下 neighbor的元素、然后遍历
neighbors = country.findall('neighbor')
neighbor_name = []
for neighbor in neighbors:
n = neighbor.get('name')
neighbor_name.append(n)
print(name, rank, neighbor_name)
印刷結果は以下のようになります。
Liechtenstein 1 ['Austria', 'Switzerland']
Singapore 4 ['Malaysia']
Panama 68 ['Costa Rica', 'Colombia']
3. イテレータ反復子
要素は iter イテレータを使用して、その下にあるすべての子を再帰的に走査します。
# 一次性获取所有名为 country 的元素、然后遍历
for country in root.iter('country'):
# 获取 country 元素中的 name 属性
name = country.get('name')
print(name)
for rank in root.iter('rank'):
# 获取 country 元素中的 name 属性
rank_n = rank.text
print(rank_n)
印刷結果は以下のようになります。
Liechtenstein
Singapore
Panama
1
4
68
4. XMLデータを辞書に変換する
xmltodict は非常に使いやすく、学習コストも低く、XML 形式のデータを素早く辞書に変換し、二次的なデータ処理を簡単に行うことができます。
コードは以下のように表示されます:
import xmltodict, json
with open('sample.xml') as f:
my_dict = xmltodict.parse(f.read())
with open('info1.json', 'w') as f:
json.dump(my_dict, f, sort_keys=False, indent=2)
開いてinfo1.json
表示します。保存されたコンテンツは次のとおりです:
{
"data": {
"@id": "world country",
"country": [
{
"@name": "Liechtenstein",
"rank": "1",
"year": "2008",
"gdppc": "141100",
"neighbor": [
{
"@name": "Austria",
"@direction": "E"
},
{
"@name": "Switzerland",
"@direction": "W"
}
]
},
{
"@name": "Singapore",
"rank": "4",
"year": "2011",
"gdppc": "59900",
"neighbor": {
"@name": "Malaysia",
"@direction": "N"
}
},
{
"@name": "Panama",
"rank": "68",
"year": "2011",
"gdppc": "13600",
"neighbor": [
{
"@name": "Costa Rica",
"@direction": "W"
},
{
"@name": "Colombia",
"@direction": "E"
}
]
}
]
}
}
で:
tag
とattrib
は辞書key
になります。たとえば、上記のdata、id、country、name、rank
などです。- ただし、
attrib
属性を持つkey
には@
シンボルが自動的に追加されますが、他のものには追加されません。 a> key
はvalue
に対応し、文字列になります。
5.xmlとして保存
xmltodict
は、 xml
を辞書形式に変換するだけでなく、次に示すように、辞書を xml
形式に変換してローカルに保存することもできます。
def saveXML():
import xmltodict
with open('info.xml', 'w') as f:
info_dict = {
'dev_info': {
'device_type': 'cisco_ios',
'username': 'admin',
'password': 'cisco',
'ip': '192.168.47.10'
}
}
f.write(xmltodict.unparse(info_dict, pretty=True))
XML ファイルとして保存した後、それを開いて次のように結果を表示します。
<?xml version="1.0" encoding="utf-8"?>
<dev_info>
<device_type>cisco_ios</device_type>
<username>admin</username>
<password>cisco</password>
<ip>192.168.47.10</ip>
</dev_info>
6. まとめ
以前、 xml
ファイルについて、 xml
とは何か、 python
での使用方法など、簡単に学習しました。 xml
ファイルとして操作および保存します。同時に、 機械に適したxml
ファイルは、人間に適した辞書表示に変換されます。 xml
確かに、表示して分析するのは簡単ではなく、少し手間がかかります。