Tôi đang cố gắng chuyển sang Python 2.7 và vì Unicode là một Giao dịch lớn ở đó, tôi sẽ thử xử lý chúng với các tệp và văn bản XML và phân tích chúng bằng thư viện xml.etree.cElementTree
. Nhưng tôi chạy qua lỗi này:Python: Unicode và ElementTree.parse
>>> import xml.etree.cElementTree as ET
>>> from io import StringIO
>>> source = """\
... <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
... <root>
... <Parent>
... <Child>
... <Element>Text</Element>
... </Child>
... </Parent>
... </root>
... """
>>> srcbuf = StringIO(source.decode('utf-8'))
>>> doc = ET.parse(srcbuf)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 56, in parse
File "<string>", line 35, in parse
cElementTree.ParseError: no element found: line 1, column 0
Điều tương tự cũng xảy ra sử dụng io.open('filename.xml', encoding='utf-8')
để vượt qua để ET.parse
:
>>> with io.open('test.xml', mode='w', encoding='utf-8') as fp:
... fp.write(source.decode('utf-8'))
...
150L
>>> with io.open('test.xml', mode='r', encoding='utf-8') as fp:
... fp.read()
...
u'<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>\n<root>\n <Parent>\n
<Child>\n <Element>Text</Element>\n </Child>\n </Parent>\n</root>\n
'
>>> with io.open('test.xml', mode='r', encoding='utf-8') as fp:
... ET.parse(fp)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<string>", line 56, in parse
File "<string>", line 35, in parse
cElementTree.ParseError: no element found: line 1, column 0
Có điều gì đó về unicode và ET phân tích cú pháp mà tôi đang thiếu ở đây?
chỉnh sửa: Rõ ràng, trình phân tích cú pháp ET không hoạt động tốt với luồng đầu vào unicode? Các công trình sau đây:
>>> with io.open('test.xml', mode='rb') as fp:
... ET.parse(fp)
...
<ElementTree object at 0x0180BC10>
Nhưng điều này cũng có nghĩa là tôi không thể sử dụng io.StringIO
nếu tôi muốn phân tích cú pháp từ một văn bản trong bộ nhớ, trừ khi tôi mã hóa nó đầu tiên vào một bộ đệm trong bộ nhớ?
Tôi không nhận ra rằng chức năng đó đã tồn tại. Mặc dù điểm nhỏ: 'fromstring' trả về' Element', trong khi 'parse' trả về' ElementTree'. – Santa
Chức năng này còn được gọi là bí danh của nó, 'XML', tức là' từ xml.etree.cElementTree nhập XML'. Bí danh này có sẵn để nó sẽ đọc độc đáo nếu bạn có một hằng số XML trong mã của bạn; bạn chỉ có thể làm 'fooDocument = XML (" "" ... "" ")'. – Glyph