Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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)

終わり

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした