简体   繁体   中英

How to add space after the text of a node but before a child element?

Here is my sample XML:

<index>
    <indextext>
        <index.text1>Here goes some text<link attribute1="this" attribute2="that">and here is a link</link></index.text1>
    </indextext>
</index>

Now my problem is that I need to separate the text of the index.text1 node and the link node.

Here's the thing. I tried doing this by getting the preceding-sibling of the link node, and I was able to actually do it, but then for some reason I lose the link attributes - in other words, that link contains attributes that enable it to link to a different document, which are in this case lost. NB: As soon as I mess with the <template match="link"> , I lose those attributes.

What I did was this:

  <xsl:template match="index.text1//link">
    <xsl:text><![CDATA[  ]]></xsl:text>
    <xsl:apply-templates/>    
  </xsl:template>

... but that doesn't work, as explained in the paragraph above.

My question would be how to somehow either select the text that comes before the link node, or how to select the link node itself and enter space before it, but preserve all the attributes?

BONUS QUESTION - is there a way for me to automatically select a bunch of different nodes that all start with the name index.text ? For example, is there a way I can automagically select index.text , index.text1 , index.text2 etc? Would index.text* work?

SOLVED - I figured out what the problem was. Basically I needed to call another template that is in the "main" code that actually handles rendering the document links. Still a lot more code to familiarize myself with!

If you know you want a space in front of all those link elements then simply do

  <xsl:template match="index.text1//link">
    <xsl:text> </xsl:text>
    <xsl:call-template name="identity"/>   
  </xsl:template>

with

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

As for wild card element matching, use

  <xsl:template match="*[starts-with(local-name(), 'index.text')]//link">
    <xsl:text> </xsl:text>
    <xsl:call-template name="identity"/>   
  </xsl:template>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM