Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
718 views
in Technique[技术] by (71.8m points)

I need to add a text value to an self closing empty tag, using XSLT

Please see the below XML. In the XML the name element is a self closing empty tag. I need to add a text value to this name element tag. This chunk of XML code might be repeated any number of times in the whole XML.

<participant typeCode="LOC">
  <participantRole classCode="SDLOC">
    <id extension="00000000-0000-0000-0000-000000000000" root="1.0"/>
    <addr nullFlavor="UNK"/>
    <playingEntity>
      <name/>
    </playingEntity>
  </participantRole>
</participant>

Expected Output: Need to add the UNK text value for the self closing empty name element tag.

<participant typeCode="LOC">
  <participantRole classCode="SDLOC">
    <id extension="00000000-0000-0000-0000-000000000000" root="1.0"/>
    <addr nullFlavor="UNK"/>
    <playingEntity>
      <name>UNK</name>
    </playingEntity>
  </participantRole>
</participant>

I need an XSLT script to achieve this requirement.

Thanks,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need an identity transformation template:

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

plus a template for the name tag:

<xsl:template match="name[not(node())]">
   <name>UNK</name>
</xsl:template>

Wrap this within the stylesheet tag, and add an xml header:

<?xml version="1.0" encoding="ISO-8859-1"?>
<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="name[not(node())]">
   <name>UNK</name>
  </xsl:template>
</xsl:stylesheet>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...