tags:

views:

73

answers:

1

Let's say I have an XML as follows.

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

I need to parse this XML into dictionary X for a/b/c and a/b'/c, but dictionary Y for a/c.

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

dictionary T
T[a_c] = X
  • Q : I'd like to make a mapping file for this in XML file using XPath. How can I do this?

I think of having mapping.xml as follows.

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

And using 'a/c' to get X, and put it in dictionary T. Is there any better ways to go?

+1  A: 

Maybe you could do this with XSLT. This stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
    <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>

Output:

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

EDIT: Pretty things a bit.

Alejandro