[英]Get children node names from one parent
给定以下XML结构
<cmap>
<tableVersion version="0" />
<cmap_format_4 platformID="0" platEncID="3" language="0">
<map code="0x20" name="space" />
<!-- SPACE -->
<!--many, many more characters-->
</cmap_format_4>
<cmap_format_0 platformID="1" platEncID="0" language="0">
<map code="0x0" name=".notdef" />
<!--many, many more characters again-->
</cmap_format_0>
<cmap_format_4 platformID="0" platEncID="3" language="0">
<!--"cmap_format_4" again-->
<map code="0x20" name="space" />
<!-- SPACE -->
<!--more "map" nodes-->
</cmap_format_4>
</cmap>
我正在尝试逐步获取cmap_format_0
级别的节点名称列表以及它们下面的所有code
和name
节点。
cmap_format_4
0x0 null
0xd CR
ox20 space
etc...
cmap_format_0
0x0 notdef
0x1 notdeaf
etc...
到目前为止,我有
charactersByFontString = "CODE\tCHAR DESC\n"
tree = ET.parse(xmlFile)
root = tree.getroot()
for map in root.iter("map"):
charactersByFontString += map.attrib["code"] + "\t"
charactersByFontString += map.attrib["name"] + "\n"
这就是我所有的代码和名称。 但是我无法获得c_format_n
的名称。
for child in root:
print child.child
因为tableversion
是它的第一个孩子,它是自动关闭的,并且没有孩子,所以它不起作用。 (另外,我不确定将一堆child
节点串在一起是否也可以。) child.sibling
给我一个错误。 如何获得cmap_format_n
格式的这些子cmap_format_n
?
我可以建议使用XSLT转换输入XML吗?
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text" encoding="UTF-8" indent="yes" />
<xsl:template match="/cmap">
<xsl:apply-templates select="*[starts-with(name(), 'cmap_')]" />
</xsl:template>
<xsl:template match="*[starts-with(name(), 'cmap_')]">
<xsl:value-of select="name()" />
<xsl:text>
</xsl:text>
<xsl:apply-templates select="map" />
<xsl:text>
</xsl:text>
</xsl:template>
<xsl:template match="map">
<xsl:apply-templates select="@code" />
<xsl:text>	</xsl:text>
<xsl:apply-templates select="@name" />
<xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>
输出( http://xsltransform.net/bFDb2Cu )
cmap_format_4 0x20 space cmap_format_0 0x0 .notdef cmap_format_4 0x20 space
在这里可以找到有关如何在Python中使用XSLT的示例。
我并不是说它不能像您尝试它那样进行(DOM遍历)-它绝对可以-XSLT更自然地适合该任务。
import xml.etree.ElementTree as ET
xmlFile = "pytest.xml"
out = "CODE\tCHAR DESC\n"
tree = ET.parse(xmlFile)
root = tree.getroot()
for child in root:
if child.tag[:4] == 'cmap':
out += child.tag + '\n'
for grandchild in child:
out += grandchild.attrib["code"] + '\t'
out += grandchild.attrib["name"] + '\n'
out += '\n'
print(out)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.