Python XML 和 XPath 排序问题

1 投票
1 回答
528 浏览
提问于 2025-04-16 02:04

假设我有一个这样的XML文件。

<a>
 <b>
  <c>A</c>
 </b>
 <bb>
  <c>B</c>
 </bb>
 <c>
  X
 </c>
</a>

我需要把这个XML解析成字典X,用于a/b/c和a/b'/c,但对于a/c则用字典Y。

dictionary X
X[a_b_c] = A
X[a_bb_c] = B

dictionary T
T[a_c] = X
  • 问:我想用XPath在这个XML文件中创建一个映射文件。我该怎么做呢?

我想把mapping.xml写成下面这样。

<mapping>
  <from>a/c</from><to>dictionary T<to>
  ....
</mapping>

然后我用'a/c'来获取X,并把它放入字典T。有没有更好的方法呢?

1 个回答

1

也许你可以用XSLT来做到这一点。这个样式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>
    <xsl:key name="dict" match="item" use="@dict"/>
    <xsl:key name="path" match="*[not(*)]" use="concat(name(../..),'/',
                                                   name(..),'/',
                                                   name())"/>
    <xsl:variable name="map">
        <item path="a/b/c" dict="X"/>
        <item path="a/bb/c" dict="X"/>
        <item path="/a/c" dict="T"/>
    </xsl:variable>
    <xsl:template match="/">
        <xsl:variable name="input" select="."/>
        <xsl:for-each select="document('')/*/xsl:variable[@name='map']/*[count(.|key('dict',@dict)[1])=1]">
            <xsl:variable name="dict" select="@dict"/>
            <xsl:variable name="path" select="../item[@dict=$dict]/@path"/>
            <xsl:value-of select="concat('dictionary ',$dict,'&#xA;')"/>
            <xsl:for-each select="$input">
                <xsl:apply-templates select="key('path',$path)">
                    <xsl:with-param name="dict" select="$dict"/>
                </xsl:apply-templates>
            </xsl:for-each>
        </xsl:for-each>
    </xsl:template>
    <xsl:template match="*">
        <xsl:param name="dict"/>
        <xsl:variable name="path" select="concat(name(../..),'_',
                                                 name(..),'_',
                                                 name())"/>
        <xsl:value-of select="concat($dict,'[',
                                     translate(substring($path,
                                                         1,
                                                         1),
                                               '_',
                                               ''),
                                     substring($path,2),'] = ',
                                     normalize-space(.),'&#xA;')"/>
    </xsl:template>
</xsl:stylesheet>

输出结果:

dictionary X
X[a_b_c] = A
X[a_bb_c] = B
dictionary T
T[a_c] = X

编辑: 让东西看起来更好一些。

撰写回答