Python:如何用utf16解析XML

2024-06-28 19:38:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把我得到的一些XML文档解析成字符串

import lxml.etree
import re
from lxml.html.soupparser import fromstring,parse

try:
    from bs4 import UnicodeDammit             # BeautifulSoup 4

    def decode_html(html_string):
        converted = UnicodeDammit(html_string)
        if not converted.unicode_markup:
            raise UnicodeDecodeError(
                "Failed to detect encoding, tried [%s]",
                ', '.join(converted.tried_encodings))
        # print converted.original_encoding
        return converted.unicode_markup

except ImportError:
    from BeautifulSoup import UnicodeDammit   # BeautifulSoup 3

    def decode_html(html_string):
        converted = UnicodeDammit(html_string, isHTML=True)
        if not converted.unicode:
            raise UnicodeDecodeError(
                "Failed to detect encoding, tried [%s]",
                ', '.join(converted.triedEncodings))
        # print converted.originalEncoding
        return converted.unicode


def tryMe(inString):

    root = fromstring(decode_html(inString))

    #print tostring(root, pretty_print=True).strip()

    backups = root.xpath(".//p3")
    nodes = root.xpath("./doc/p1/p2/p3[contains(text(),'ABC')]//preceding::p1//p3")

    if not nodes:

        print "No XYZ"
        nodes = root.xpath("./doc/p1/p2/p3[contains(text(),'XYZ')]//preceding::p1//p3") 

        if not nodes:

            print "No ABC"
            return " ".join([re.sub('[\s+]', ' ', para.text.strip()) for para in backups])

        else:

            return " ".join([re.sub('[\s+]', ' ', para.text.strip()) for para in nodes])
    else:
        return " ".join([re.sub('[\s+]', ' ', para.text.strip()) for para in nodes])

基本上,我想查找一个文本为ABC的标记<p3>。如果找到这个节点,我将忽略后面的所有内容。因此xpath。否则,我将查找带有文本XYZ的标记<p3>。如果这被发现,我会忽略这之后发生的一切。否则,我只处理所有<p3>节点并返回。在

这对于utf-8文档很好,但对于utf-16则不行。对于任何utf-16文档,我总是得到一个空字符串。尽管我可以看到标记<p3>的xml节点有ABC和XYZ这样的文本。我注意到这并不是预期的

^{pr2}$

utf-16文档文本显示为

&lt;p3&gt;ABC&lt;/p3&gt;

因此lxml.etree无法将其解析为正确的xml。在

我该怎么解决这个问题?在


Tags: text文档importrereturnhtmlrootnodes