PythonのXML解析ライブラリlxml
を使おうとしたら、以下のエラーが出てしまった。
ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.
ソースコードは以下のような感じに手元にあるXMLファイルを読み込もうとしました。
from lxml import etree
with open('sample.xml', 'r', encoding='utf-8') as f:
xml = f.read()
xml_object = etree.fromstring(xml)
read()
でファイルを読み込んだ場合type
は<class 'str'>
なので、素のstr
型に変換するかbyte
形式にするかしないといけない
以下のようにしてbyte
に変換すればよいと思ったら以下のようになんかエラーが出た。
with open('sample.xml', 'r', encoding='utf-8') as f:
xml = f.read()
print(type(xml))
xml = xml.encode('utf-8')
print(type(xml))
xml_object = etree.fromstring(xml)
# <class 'str'>
# <class 'bytes'>
# Traceback (most recent call last):
# 〜省略〜
# XMLSyntaxError: xmlParseEntityRef: no name, line xxxxx, column xxx
調べてみると、XMLタグ内で囲まれた文字列内に&
があるとXMLSytaxError
がでるようです。
なので、雑な対応でありますが、一旦&
(半角)を&
(全角)に変換して対応しました。
これでエラーは解決。
with open('sample.xml', 'r', encoding='utf-8') as f:
xml = f.read().replace("&","&")
xml = xml.encode('utf-8')
xml_object = etree.fromstring(xml)
終わり