【问题标题】:How to use a local DTD file to parse an XML file using lxml?如何使用本地 DTD 文件使用 lxml 解析 XML 文件?
【发布时间】:2018-07-24 11:04:09
【问题描述】:

我正在尝试在 python 中使用 lxml 解析 DBLP 数据集。但是它给出了这个错误:

lxml.etree.XMLSyntaxError: 实体 'uuml' 未定义,第 54 行,第 43 列

DBLP 确实提供了一个DTD 文件来定义实体here。如何使用该文件来解析 DBLP XML 文档?

这是我当前的代码:

filename = sys.argv[1]
dtd_name = sys.argv[2]
db_name = sys.argv[3]

conn = sqlite3.connect(db_name)

dblp_record_types_for_publications = ('article', 'inproceedings', 'proceedings', 'book', 'incollection',
    'phdthesis', 'masterthesis', 'www')

# read dtd
dtd = ET.DTD(dtd_name) #pylint: disable=E1101

# get an iterable
context = ET.iterparse(filename, events=('start', 'end'), load_dtd=True, #pylint: disable=E1101
    resolve_entities=True) 

# turn it into an iterator
context = iter(context)

# get the root element
event, root = next(context)

n_records_parsed = 0
for event, elem in context:
    if event == 'end' and elem.tag in dblp_record_types_for_publications:
        pub_year = None
        for year in elem.findall('year'):
            pub_year = year.text
        if pub_year is None:
            continue

        pub_title = None
        for title in elem.findall('title'):
            pub_title = title.text
        if pub_title is None:
            continue

        pub_authors = []
        for author in elem.findall('author'):
            if author.text is not None:
                pub_authors.append(author.text)

        # print(pub_year)
        # print(pub_title)
        # print(pub_authors)
        # insert the publication, authors in sql tables
        pub_title_sql_str = pub_title.replace("'", "''")
        pub_author_sql_strs = []
        for author in pub_authors:
            pub_author_sql_strs.append(author.replace("'", "''"))

        conn.execute("INSERT OR IGNORE INTO publications VALUES ('{title}','{year}')".format(
            title=pub_title_sql_str,
            year=pub_year))
        for author in pub_author_sql_strs:
            conn.execute("INSERT OR IGNORE INTO authors VALUES ('{name}')".format(name=author))
            conn.execute("INSERT INTO authored VALUES ('{author}','{publication}')".format(author=author,
                publication=pub_title_sql_str))

        elem.clear()
        root.clear()

        n_records_parsed += 1
        print("No. of records parsed: {}".format(n_records_parsed))

conn.commit()
conn.close()

【问题讨论】:

  • 如果 XML 文档有 doctype 声明 (<!DOCTYPE dblp SYSTEM "dblp.dtd">) 并且如果 dblp.dtd 与 XML 文件在同一目录中,并且如果使用了 load_dtd=True,那么我不明白任何语法错误。我认为在这种情况下使用dtd = ET.DTD(dtd_name) 没有任何效果。

标签: python xml lxml dtd


【解决方案1】:

将 DTD 文件与 XML 文件保存在同一目录中并确保 DTD 文件名和 XML 文档的 doctype 声明 (<!DOCTYPE dblp SYSTEM "dblp.dtd">) 中的 DTD 文件名匹配后,如 mzjn 在cmets,它不再给出语法错误。

【讨论】:

    【解决方案2】:

    您可以添加自定义 URI 解析器https://lxml.de/resolvers.html

    class DTDResolver(etree.Resolver):
        def resolve(self, system_url, public_id, context):
            return self.resolve_filename(os.path.join("/path/to/dtd/file", system_url), context)
    
    context.resolvers.add(DTDResolver())
    

    【讨论】:

      猜你喜欢
      • 2013-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-18
      • 2014-08-22
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多