【医用画像データ処理】XMLファイル形式の処理概要

xml(Extensible Markup Language,简称:XML)Extensible Markup Language はnetconf構成ファイル形式です。これは本質的に階層的なデータ形式であり、最も自然な表現はそれをツリーに解析することです。ただし、xmlそのようなラベル データは「機械」の認識を対象としており、「人間」の認識には役に立たないので、もっと面倒なようです。

Netconf ワーキング グループは 2003 年 5 月に設立されました。このワーキング グループは主に、新しい XML ベースのネットワーク構成 (NETCONF) プロトコルを提案することを目的としています。設立。

Python組み込み API:xml.etree.ElementTree ファイルを解析できますxml ドキュメント全体をツリー構造に解析します。 はこのツリー構造内の単一のノードを表します。 ElementTreexmlElement

官方文件地址: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"
textElementcisco_ios
child elementsxmlcountry

例:

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): 遍历Elementchild,可以指定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"
          }
        ]
      }
    ]
  }
}

で:

  • tagattrib は辞書 key になります。たとえば、上記の data、id、country、name、rank などです。
  • ただし、attrib 属性を持つ key には@ シンボルが自動的に追加されますが、他のものには追加されません。 a>
  • keyvalue に対応し、文字列になります。

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確かに、表示して分析するのは簡単ではなく、少し手間がかかります。

おすすめ

転載: blog.csdn.net/wsLJQian/article/details/134058924