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)
終わり