LoginSignup
2
0

More than 5 years have passed since last update.

【lxml】Unicode strings with encoding declaration are not supported.

Last updated at Posted at 2018-09-11

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)

終わり

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0