我正在使用 Python (minidom) 来解析一个 XML 文件,该文件打印一个看起来像这样的层次结构(这里使用缩进来显示重要的层次关系):
My Document
Overview
Basic Features
About This Software
Platforms Supported
相反,程序在节点上迭代多次并生成以下打印重复节点。(查看每次迭代的节点列表,很明显它为什么会这样做,但我似乎无法找到一种方法来获取我正在寻找的节点列表。)
My Document
Overview
Basic Features
About This Software
Platforms Supported
Basic Features
About This Software
Platforms Supported
Platforms Supported
这是 XML 源文件:
<?xml version="1.0" encoding="UTF-8"?>
<DOCMAP>
<Topic Target="ALL">
<Title>My Document</Title>
</Topic>
<Topic Target="ALL">
<Title>Overview</Title>
<Topic Target="ALL">
<Title>Basic Features</Title>
</Topic>
<Topic Target="ALL">
<Title>About This Software</Title>
<Topic Target="ALL">
<Title>Platforms Supported</Title>
</Topic>
</Topic>
</Topic>
</DOCMAP>
这是 Python 程序:
import xml.dom.minidom
from xml.dom.minidom import Node
dom = xml.dom.minidom.parse("test.xml")
Topic=dom.getElementsByTagName('Topic')
i = 0
for node in Topic:
alist=node.getElementsByTagName('Title')
for a in alist:
Title= a.firstChild.data
print Title
我可以通过不嵌套“主题”元素来解决问题,方法是将较低级别的主题名称更改为“SubTopic1”和“SubTopic2”之类的名称。但是,我想利用内置的 XML 层次结构而不需要不同的元素名称;似乎我应该能够嵌套“主题”元素,并且应该有某种方法可以知道我当前正在查看的“主题”级别。
我尝试了许多不同的 XPath 函数,但没有取得多大成功。