2010-07-30 7 views
1

다음과 같이 XML이 있다고 가정 해 봅시다.것들을 정렬하는 Python XML과 XPath

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

나는 a/c를위한 사전 A/B/C에 대한 X 및 A/B '/ C,하지만 사전 Y로이 XML을 구문 분석 할 필요가있다.

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

dictionary T 
T[a_c] = X 
  • Q : 나는 XPath를 사용하여 XML 파일에서이에 대한 매핑 파일을하고 싶습니다. 어떻게해야합니까?

다음과 같이 mapping.xml이 있다고 생각합니다.

'a/c'를 사용하여 X를 가져 와서 사전 T에 넣으십시오. 더 좋은 방법이 있습니까?

답변

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="https://stackoverflow.com/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 

편집 : 예쁜 것들을 조금.

관련 문제