Python ElementTree 实战:逐条解析 XML 商品目录并导出 JSONL

10-20 4阅读

拿到内部系统导出的商品目录时,我们常常只需要编号、名称和备注,不需要把整棵 XML 树交给后续程序。本文用 Python 标准库写一个本地转换器:按记录提取、明确校验、逐行输出,并在处理后清理节点。示例不访问网络,也不把“增量解析”包装成无限大小文件的通行证。

Python ElementTree 实战:逐条解析 XML 商品目录并导出 JSONL
AI 生成概念插画:表示本地目录的逐条提取与清理,不是程序截图或内存性能测试图。

先限定任务,再选择解析方式

输入必须是来源可信、内容可控的本地普通文件,例如自己生成并核对过的内部导出。文件在硬盘上,不等于文件可信;用户上传、邮件附件和陌生供应商传来的 XML,不能直接套用本方案。程序按二进制读取,让解析器处理 XML 声明里的编码,不自行猜测文本编码。

目录约定为一个 catalog 根元素,下面直接放 item;每条记录只有 id 属性、必填的纯文本 title,以及可选的纯文本 note。字段前后空白会被去掉,空名称、重复字段、未知字段和嵌套富文本都报错。程序不做 XML Schema 校验、不检查全局编号唯一性,也不把根节点层级的文本当业务数据。

将下面的样例保存为 catalog.xml。第一条备注存在但为空,第二条完全没有备注,第三条包含转义后的连接符。这三种输入正好能检验转换时有没有丢失语义。

<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="urn:catalog:v1">
  <item id="p-101"><title>方格笔记本</title><note/></item>
  <item id="p-102"><title>木质铅笔</title></item>
  <item id="p-103"><title>帆布笔袋</title><note>蓝色 &amp; 米白</note></item>
</catalog>

命名空间与空值:别靠“看起来一样”判断

本例命名空间是 urn:catalog:v1。程序用完整名称比较根节点和记录节点,用自定义前缀 c 查询字段。因此,输入改用 x:catalog、x:item 这样的前缀,只要 URI 不变,结果仍相同;完全没有命名空间或使用另一个 URI 则会被拒绝。这不是去掉前缀后比较字符串。参见官方命名空间说明。

查不到 note 时返回 None,输出 JSON 时变成 null;找到空 note 时返回空字符串。不要写 if not node 来判断是否找到元素,因为元素的布尔值和它是否有子元素有关。本例明确写 node is None,再单独检查文本。空白备注也归为空字符串,这是本转换器主动选择的清洗规则,而不是 XML 替我们决定的含义。

完整转换器:在记录结束后提取

保存以下文件为 catalog_xml.py。start 事件只用于识别层级和检查根节点;等到 item 的 end 事件才读取字段。代码先构造独立字典,再清理原节点,最后交给调用方,避免调用方持有一批随后被清空的 Element 对象。事件时机可对照iterparse 文档。

"""Extract JSONL from a trusted, local XML catalogue. Python 3.10+."""
import argparse
import json
import sys
import xml.etree.ElementTree as ET
from contextlib import closing

URI = "urn:catalog:v1"
NS = {"c": URI}
ROOT = f"{{{URI}}}catalog"
ITEM = f"{{{URI}}}item"
FIELDS = {f"{{{URI}}}title", f"{{{URI}}}note"}


class CatalogError(ValueError):
    pass


class ByteBudget:
    def __init__(self, source, limit):
        self.source = source
        self.remaining = limit

    def read(self, size=-1):
        size = self.remaining + 1 if size < 0 else min(size, self.remaining + 1)
        data = self.source.read(size)
        if len(data) > self.remaining:
            raise CatalogError("input exceeds max_bytes")
        self.remaining -= len(data)
        return data


def field_text(item, name, required=False):
    nodes = item.findall(f"c:{name}", NS)
    if len(nodes) > 1:
        raise CatalogError(f"duplicate field: {name}")
    node = item.find(f"c:{name}", NS)
    if node is None:
        if required:
            raise CatalogError(f"missing field: {name}")
        return None
    if len(node) or node.attrib:
        raise CatalogError(f"field must be plain text: {name}")
    value = (node.text or "").strip()
    if required and not value:
        raise CatalogError(f"empty field: {name}")
    return value


def extract_item(item):
    if set(item.attrib) != {"id"}:
        raise CatalogError("item requires only an id attribute")
    item_id = item.get("id", "").strip()
    if not item_id:
        raise CatalogError("empty item id")
    if (item.text or "").strip():
        raise CatalogError("unexpected item text")
    for child in item:
        if child.tag not in FIELDS or (child.tail or "").strip():
            raise CatalogError("unexpected item content")
    return {"id": item_id, "title": field_text(item, "title", True),
            "note": field_text(item, "note")}


def iter_catalog(path, *, max_bytes=20 * 1024 * 1024,
                 max_records=100000, max_depth=16):
    """Yield copied dictionaries. Not a parser for untrusted XML."""
    if min(max_bytes, max_records, max_depth) < 1:
        raise CatalogError("limits must be positive")
    count = depth = 0
    root = None
    with open(path, "rb") as source:
        events = ET.iterparse(ByteBudget(source, max_bytes),
                              events=("start", "end"))
        for event, elem in events:
            if event == "start":
                depth += 1
                if depth > max_depth:
                    raise CatalogError("input exceeds max_depth")
                if depth == 1:
                    root = elem
                    if root.tag != ROOT or root.attrib:
                        raise CatalogError("expected namespaced catalog root")
                elif depth == 2 and elem.tag != ITEM:
                    raise CatalogError("catalog may contain only direct item children")
                continue
            if depth == 2:
                count += 1
                if count > max_records:
                    raise CatalogError("input exceeds max_records")
                record = extract_item(elem)
                # Clear payload, then unlink the empty shell from its parent.
                elem.clear()
                root.remove(elem)
                depth -= 1
                yield record
            else:
                depth -= 1


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("path", help="trusted local XML path; never a URL")
    parser.add_argument("--max-bytes", type=int, default=20 * 1024 * 1024)
    parser.add_argument("--max-records", type=int, default=100000)
    parser.add_argument("--max-depth", type=int, default=16)
    args = parser.parse_args(argv)
    try:
        with closing(iter_catalog(args.path, max_bytes=args.max_bytes,
                                  max_records=args.max_records,
                                  max_depth=args.max_depth)) as records:
            for record in records:
                print(json.dumps(record, ensure_ascii=False))
    except (OSError, ET.ParseError, CatalogError) as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 2
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

清空节点,还要移除根节点里的引用

只调用 elem.clear() 会删除内容,但父节点仍能留着一个空壳。这里知道所有 item 都是根的直接子节点,所以随后执行 root.remove(elem)。这不是任意 XML 都能照搬的模板:如果记录被分组包裹,需要维护真实父节点;如果一个记录内部还有子记录,过早清理会破坏外层提取。

也不要在每个字段结束时清理 title 或 note,外层 item 还要读取它们。当前实现保留正在构建的记录,并允许解析器缓冲、预读;一个特别大的记录、很长的根文本以及调用方把所有结果放进列表,都可能增加内存。本例没有做峰值内存基准,不承诺固定内存,更不声称能无条件处理任意规模数据。当前官方文档也区分了清理内容与移除子节点。

运行、输出与失败约定

以下命令在两个文件所在目录运行,使用 UTF-8 模式便于跨平台保留中文。输出是一行一个 JSON 对象,而不是一个 JSON 数组。逐条序列化后补换行是本程序定义的 JSONL 格式;不要把连续输出的对象误认为单个合法 JSON 文档。参见标准库 JSON 的流格式提醒。

python -X utf8 catalog_xml.py catalog.xml
python -X utf8 catalog_xml.py catalog.xml --max-records 2
python -X utf8 catalog_xml.py catalog.xml --max-bytes 10

正常运行的实际输出如下,退出码为零。注意两条备注的空字符串和 null 不同,中文及连接符已经正确还原。

{"id": "p-101", "title": "方格笔记本", "note": ""}
{"id": "p-102", "title": "木质铅笔", "note": null}
{"id": "p-103", "title": "帆布笔袋", "note": "蓝色 & 米白"}

格式损坏抛出 ParseError;文件打不开归入 OSError;业务字段和额度错误归入 CatalogError。命令行把错误写到标准错误,返回退出码二,不把失败伪装成空目录。解析异常通常包含行列信息,定位方式见ParseError 文档。

这里的输出不是事务:如果尾部 XML 损坏,前面已经输出的记录不会撤回。下游不能只看“有文件、有几行”就认定成功,必须检查退出码。若业务要求全有或全无,应先输出到独立临时文件,完整成功后再由调用流程替换目标文件,不直接覆盖正式结果。

额度有用,但不是安全边界

默认额度为二十 MiB 输入字节、十万条记录、十六层元素深度。字节预算包装读取接口,在实际读取时计数,不只依赖文件大小预检查;精确等于上限允许,超过就报错。深度和记录数在事件阶段检查,因此不能被解释为解析器内部的硬性内存或 CPU 上限。即使很小的输入,也可能因 XML 特性或极端结构造成风险。

对于不可信 XML,请阅读Python 官方 XML 安全说明,评估适合的加固解析器、运行时更新和进程资源隔离。官方推荐服务器处理不可信 XML 时考虑 defusedxml;它不是本文的标准库依赖。本文没有做 DTD 安全过滤,也不以简单字符串扫描充当防护,更不声称所有 XML 模块都有相同风险。

另外,iterparse 仍会阻塞读取,不适合直接塞进要求非阻塞的事件循环。本例明确拥有文件句柄,用 with 负责关闭;命令行又用 closing 管理生成器。其他调用方如果只消费一部分记录,也应使用 closing 或显式关闭生成器。相关用法见contextlib.closing 文档。

把边界行为变成可执行测试

将以下代码保存为 test_catalog_xml.py,与转换器放在同一目录。测试使用临时文件,不需要下载数据;除了普通结果,还覆盖命名空间前缀、缺失与空值、错误字段、额度、清理及移除、成功命令行和尾部损坏后的部分输出。模拟事件用例检查具体清理动作,不拿它冒充内存压测。

import json
import pathlib
import subprocess
import sys
import tempfile
import unittest
import xml.etree.ElementTree as ET
from contextlib import closing
from unittest.mock import patch

import catalog_xml as app


class CatalogTests(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory()
        self.addCleanup(self.tmp.cleanup)
        self.path = pathlib.Path(self.tmp.name) / "input.xml"

    def write(self, body, namespace=app.URI):
        text = f'<catalog xmlns="{namespace}">{body}</catalog>'
        self.path.write_text(text, encoding="utf-8")
        return text

    def rows(self, body, **limits):
        self.write(body)
        return list(app.iter_catalog(self.path, **limits))

    def bad(self, body, pattern):
        with self.assertRaisesRegex(app.CatalogError, pattern):
            self.rows(body)

    def test_normal_unicode_and_whitespace(self):
        self.assertEqual(self.rows('<item id=" a "><title> 纸笔 </title></item>'),
                         [{"id": "a", "title": "纸笔", "note": None}])

    def test_present_empty_note(self):
        self.assertEqual(self.rows('<item id="a"><title>A</title><note/></item>')[0]["note"], "")

    def test_present_whitespace_note(self):
        self.assertEqual(self.rows('<item id="a"><title>A</title><note>  </note></item>')[0]["note"], "")

    def test_note_with_entity(self):
        self.assertEqual(self.rows('<item id="a"><title>A</title><note>A &amp; B</note></item>')[0]["note"], "A & B")

    def test_empty_catalog(self):
        self.assertEqual(self.rows(""), [])

    def test_prefixed_namespace(self):
        self.path.write_text(f'<x:catalog xmlns:x="{app.URI}"><x:item id="a"><x:title>A</x:title></x:item></x:catalog>', encoding="utf-8")
        self.assertEqual(list(app.iter_catalog(self.path))[0]["title"], "A")

    def test_wrong_namespace(self):
        self.write("", namespace="urn:wrong")
        with self.assertRaisesRegex(app.CatalogError, "root"):
            list(app.iter_catalog(self.path))

    def test_missing_title(self):
        self.bad('<item id="a"/>', "missing field: title")

    def test_empty_title(self):
        self.bad('<item id="a"><title/></item>', "empty field: title")

    def test_missing_id(self):
        self.bad('<item><title>A</title></item>', "id attribute")

    def test_empty_id(self):
        self.bad('<item id=" "><title>A</title></item>', "empty item id")

    def test_duplicate_field(self):
        self.bad('<item id="a"><title>A</title><title>B</title></item>', "duplicate")

    def test_unknown_field(self):
        self.bad('<item id="a"><title>A</title><price>1</price></item>', "unexpected")

    def test_nested_markup(self):
        self.bad('<item id="a"><title>A<b>B</b></title></item>', "plain text")

    def test_nested_item_not_top_level(self):
        self.bad('<group><item id="a"><title>A</title></item></group>', "direct item")

    def test_byte_budget_exact_and_over(self):
        text = self.write('<item id="a"><title>纸</title></item>')
        size = len(text.encode("utf-8"))
        self.assertEqual(len(list(app.iter_catalog(self.path, max_bytes=size))), 1)
        with self.assertRaisesRegex(app.CatalogError, "max_bytes"):
            list(app.iter_catalog(self.path, max_bytes=size - 1))

    def test_record_budget(self):
        body = '<item id="a"><title>A</title></item>' * 2
        self.write(body)
        with closing(app.iter_catalog(self.path, max_records=1)) as rows:
            self.assertEqual(next(rows)["id"], "a")
            with self.assertRaisesRegex(app.CatalogError, "max_records"):
                next(rows)

    def test_depth_budget(self):
        with self.assertRaisesRegex(app.CatalogError, "max_depth"):
            self.rows('<item id="a"><title>A</title></item>', max_depth=2)

    def test_invalid_limit(self):
        with self.assertRaisesRegex(app.CatalogError, "positive"):
            self.rows("", max_records=0)

    def test_parse_error(self):
        self.path.write_text(f'<catalog xmlns="{app.URI}"><item>', encoding="utf-8")
        with self.assertRaises(ET.ParseError):
            list(app.iter_catalog(self.path))

    def test_clears_and_unlinks_processed_item(self):
        root = ET.Element(app.ROOT)
        item = ET.SubElement(root, app.ITEM, id="a")
        title = ET.SubElement(item, f"{{{app.URI}}}title")
        title.text = "A"
        events = [("start", root), ("start", item), ("start", title),
                  ("end", title), ("end", item), ("end", root)]
        self.write("")
        with patch.object(app.ET, "iterparse", return_value=iter(events)):
            self.assertEqual(list(app.iter_catalog(self.path))[0]["title"], "A")
        self.assertEqual(len(root), 0)
        self.assertEqual((len(item), item.attrib, item.text), (0, {}, None))

    def cli(self, *args):
        script = pathlib.Path(app.__file__)
        return subprocess.run([sys.executable, str(script), str(self.path), *args],
                              capture_output=True, text=True, encoding="utf-8")

    def test_cli_success(self):
        self.write('<item id="a"><title>纸笔</title></item>')
        result = self.cli()
        self.assertEqual((result.returncode, result.stderr), (0, ""))
        self.assertEqual(json.loads(result.stdout)["title"], "纸笔")

    def test_cli_failure_missing_file(self):
        result = self.cli()
        self.assertEqual(result.returncode, 2)
        self.assertTrue(result.stderr.startswith("error:"))
        self.assertEqual(result.stdout, "")

    def test_cli_failure_malformed_tail_has_partial_output(self):
        self.path.write_text(f'<catalog xmlns="{app.URI}"><item id="a"><title>A</title></item><item>', encoding="utf-8")
        result = self.cli()
        self.assertEqual(result.returncode, 2)
        self.assertIn("error:", result.stderr)
        self.assertEqual(json.loads(result.stdout)["id"], "a")


if __name__ == "__main__":
    unittest.main()

运行 python -m unittest -v。本次在 Python 3.12.14 实测二十四项全部通过;命令行另测正常文件、损坏文件和超出字节额度,退出码分别为零、二、二。完整命令行测试会启动真正的子进程,而不是只测试函数返回值。测试入口可参考unittest 官方文档。

落地前最值得确认的不是把额度调得多大,而是输入契约是否与导出系统一致、空值含义是否符合业务,以及下游是否正确处理失败。把这三件事说清楚,逐条读取、及时释放和稳定交付才形成完整的小工具。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。