Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

nodes - Remove elements based on other element's value -- XSLT

I have a style-sheet that I am using to remove certain elements based on the value of an other element. However, it is not working ...

Sample Input XML

<Model>
<Year>1999</Year>
<Operation>ABC</Operation>
<Text>Testing</Text>
<Status>Ok</Status>
</Model>

If Operation value is 'ABC' then remove Text and Status nodes from XML. And gives the following output.

<Model>
<Year>1999</Year>
<Operation>ABC</Operation>
</Model>

Here is my style sheet that I am using but it is removing Text and Status nodes from all XMLs even when operation is not 'ABC'.

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <xsl:strip-space elements="*"/>
  <xsl:variable name="ID" select="//Operation"/>
  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="Text | Status">
    <xsl:if test ="$ID ='ABC'">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

Thanks in Advance

How would I do the same when namespace is present like

<ns0:next type="Sale" xmlns:ns0="http://Test.Schemas.Inside_Sales">
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Here is a complete XSLT transformation -- short and simple (no variables, no xsl:if, xsl:choose, xsl:when, xsl:otherwise):

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

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

 <xsl:template match=
 "*[Operation='ABC']/Text | *[Operation='ABC']/Status"/>
</xsl:stylesheet>

When this transformation is applied on the provided XML document:

<Model>
    <Year>1999</Year>
    <Operation>ABC</Operation>
    <Text>Testing</Text>
    <Status>Ok</Status>
</Model>

the wanted, correct result is produced:

<Model>
   <Year>1999</Year>
   <Operation>ABC</Operation>
</Model>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...