构建XML文档结构的图形
我想制作一个图表,显示在某个XML文档中,哪些标签是其他标签的子标签。
我写了一个函数,可以获取在lxml.etree树中,某个标签的唯一子标签集合:
def iter_unique_child_tags(root, tag):
"""Iterates through unique child tags for all instances of tag.
Iteration starts at `root`.
"""
found_child_tags = set()
instances = root.iterdescendants(tag)
from itertools import chain
child_nodes = chain.from_iterable(i.getchildren() for i in instances)
child_tags = (n.tag for n in child_nodes)
for t in child_tags:
if t not in found_child_tags:
found_child_tags.add(t)
yield t
请问有没有通用的图表生成器,可以和这个函数一起使用,来生成一个dot文件或者其他格式的图表呢?
我也隐约觉得,可能有某个工具是专门为这个目的设计的;那可能是什么呢?
1 个回答
3
我最后选择了使用 python-graph 这个库。同时,我还用了 argparse 来创建一个命令行界面,这个界面可以从XML文件中提取一些基本信息,并生成 pydot 支持的图像格式。这个项目叫做 xmlearn,用起来还挺有用的:
usage: xmlearn [-h] [-i INFILE] [-p PATH] {graph,dump,tags} ...
optional arguments:
-h, --help show this help message and exit
-i INFILE, --infile INFILE
The XML file to learn about. Defaults to stdin.
-p PATH, --path PATH An XPath to be applied to various actions.
Defaults to the root node.
subcommands:
{graph,dump,tags}
dump Dump xml data according to a set of rules.
tags Show information about tags.
graph Build a graph from the XML tags relationships.