开发者

Need to add a block to the existing xml portin using xsl

i have a block as below.

<items>
<item>
<itemName>Pen</itemName>
&l开发者_运维知识库t;cost>200</cost>
</item>
<item>
<itemName>Book</itemName>
<cost>100</cost>
</item>
<item>
<itemName>Bag</itemName>
<cost>250</cost
</item>
</items>

I need to go through the above block and if i did not find any item with the name pencil then i need to add pencil as below.

<item>
<itemName>Pencil</itemName>
<cost>20</cost>
</item>

Please provide me some pointers. logic should handle the following senario also.

<items>
<item/>
</items>

In the above senario the output needs to be as below.

<items>
<item>
<itemName>Pencil</itemName>
<cost>20</cost>
</item>
</items>


This can be achieved by means of the identity transform, with some extra templates to match the situations you require.

To match an items element which does not contain a Pencil item, you could use the following

<xsl:template match="items[not(item[itemName='Pencil'])]">

Additionally, you need to ignore empty item elements, like so

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

Putting this altogether gives the following XSLT

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="xml" indent="yes"/>

   <xsl:template match="items[not(item[itemName='Pencil'])]">
      <xsl:copy>
         <item>
            <itemName>Pencil</itemName>
            <cost>20</cost>
         </item>
         <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
   </xsl:template>

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

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

When applied to your input XML, the output is as follows:

<items>
   <item>
      <itemName>Pencil</itemName>
      <cost>20</cost>
   </item>
   <item>
      <itemName>Pen</itemName>
      <cost>200</cost>
   </item>
   <item>
      <itemName>Book</itemName>
      <cost>100</cost>
   </item>
   <item>
      <itemName>Bag</itemName>
      <cost>250</cost>
   </item>
</items>

Additionally, when the input is as follows:

<items>
  <item/>
</items>   

The output will be as follows:

<items>
  <item>
    <itemName>Pencil</itemName>
    <cost>20</cost>
  </item>
</items>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜