2017-03-28 3 views
3

Ich versuche, meine erste XSLT zu schreiben. Es muss alle bind Elemente finden, wo das Attribut ref mit "$ .root" beginnt und dann ".newRoot" einfügt. Ich habe es geschafft, für das spezifische Attribut zu passen, aber ich verstehe nicht, wie ich es erhalten kann, um einen aktualisierten Attributwert zu drucken.Edit Wert in bestimmten Attribut mit XSLT

Eingabebeispiel XML:

<?xml version="1.0" encoding="utf-8" ?> 
<top> 
    <products> 
     <product> 
      <bind ref="$.root.other0"/> 
     </product> 
     <product> 
      <bind ref="$.other1"/> 
     </product> 
     <product> 
      <bind ref="$.other2"/> 
     </product> 
     <product> 
      <bind ref="$.root.other3"/> 
     </product> 
    </products> 
</top> 

Meine XSL so weit:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

    <xsl:template match="@*|node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="bind[starts-with(@ref,'$.root')]/@ref"> 
     <xsl:attribute name="ref">$.newRoot<xsl:value-of select="bind/@ref" /></xsl:attribute> 
    </xsl:template> 
</xsl:stylesheet> 

Die XML Ich möchte von dem Eingang produzieren:

<?xml version="1.0" encoding="utf-8" ?> 
<top> 
    <products> 
     <product> 
      <bind ref="$.newRoot.root.other0"/> 
     </product> 
     <product> 
      <bind ref="$.other1"/> 
     </product> 
     <product> 
      <bind ref="$.other2"/> 
     </product> 
     <product> 
      <bind ref="$.newRoot.root.other3"/> 
     </product> 
    </products> 
</top> 

Antwort

6

Statt:

<xsl:template match="bind[starts-with(@ref,'$.root')]/@ref"> 
    <xsl:attribute name="ref">$.newRoot<xsl:value-of select="bind/@ref" /></xsl:attribute> 
</xsl:template> 

Versuch:

<xsl:template match="bind[starts-with(@ref,'$.root')]/@ref"> 
    <xsl:attribute name="ref">$.newRoot.root<xsl:value-of select="substring-after(., '$.root')" /></xsl:attribute> 
</xsl:template> 

oder (gleiche Sache in eine bequemere Syntax):

<xsl:template match="bind/@ref[starts-with(., '$.root')]"> 
    <xsl:attribute name="ref"> 
     <xsl:text>$.newRoot.root</xsl:text> 
     <xsl:value-of select="substring-after(., '$.root')" /> 
    </xsl:attribute> 
</xsl:template> 

Beachten Sie die Verwendung von . auf den aktuellen Knoten zu verweisen. In Ihrer Version wählt die Anweisung <xsl:value-of select="bind/@ref" /> nichts aus, da das Attribut ref bereits der aktuelle Knoten ist - und keine Kinder enthält.

+0

Danke! Wenn ref-Attribut der aktuelle Knoten ist, warum muss ich ihn im xsl: attribute-Element benennen? –

+1

@ Björn Wenn Sie möchten, können Sie den Namen des aktuellen Knotens berechnen, anstatt ihn wörtlich zu spezifizieren: ''. –

Verwandte Themen