xmltodict で dict(辞書)として読み取るのも簡単で良いけど、
FastAPI を使う案件なら、データ検証ライブラリ pydantic で構成するクラスとして
読込みたいものである。
pydantic-xml を使う。
pydantic-xml → https://pypi.org/project/pydantic-xml/
サンプル
以下のXML
<?xml version="1.0" encoding="UTF-8" ?> <Customer> <name type="A">山田</name> <age>32</age> <items type="list"> <tad>Red</tad> <tad>Blue</tad> </items> </Customer>
Customerタグ、nameタグ、ageタグ、itemsタグ、tadタグ
各タグに合わせたクラスを用意して、
from pydantic_xml import BaseXmlModel, attr, element from typing import List class Name(BaseXmlModel): type: str = attr(name="type") value: str class Age(BaseXmlModel): value: int class Tad(BaseXmlModel): value: str class Items(BaseXmlModel): type: str = attr("type") tadlist: List[Tad] = element(tag="tad", default=[]) class Customer(BaseXmlModel): name: Name = element(tag="name") age: Age = element(tag="age") items: Items = element(tag='items')
xmlstr = """<?xml version="1.0" encoding="UTF-8" ?> <Customer> <name type="A">山田</name> <age>32</age> <items type="list"> <tad>Red</tad> <tad>Blue</tad> </items> </Customer> """ customer = Customer.from_xml(xmlstr) print(customer)
print の結果
name=Name(type='A', value='山田') age=Age(value=32) items=Items(type='list', tadlist=[Tad(value='Red'), Tad(value='Blue')])










