xslt - parsing xml to skip tags -
i have following stylesheet skip tags xyz_1, xyz_2.
- how work xyz_*
- also, in output tags skipped have empty lines, how suppress them.
thanks in advance.
<?xml version="1.0" ?> <xsl:stylesheet version="2.0" xmlns="http://www.w3.org/1999/xsl/transform" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:output method="html" indent="no" encoding="utf-8" omit-xml-declaration="yes" /> <xsl:template match="*"> <xsl:copy> <xsl:copy-of select="@*" /> <xsl:apply-templates /> </xsl:copy> </xsl:template> <xsl:template match="xyz_1" /> <xsl:template match="xyz_2" /> </xsl:stylesheet>
here sample xml
<?xml version="1.0" encoding="utf-8"?> <tags> <tag> <tag1>tagname1</tag1> <xyz_1> <name>1.pdf</name> </xyz_1> <xyz_2> <c_name>chart1.gif</c_name> </xyz_2> </tag> </tags>
the output comes out
<?xml version="1.0" encoding="utf-8"?> <tags> <tag> <tag1>tagname1</tag1> </tag> </tags>
use:
<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="*[starts-with(name(), 'xyz_')]"/> </xsl:stylesheet>
when applied on provided xml document:
<?xml version="1.0" encoding="utf-8"?> <tags> <tag> <tag1>tagname1</tag1> <xyz_1> <name>1.pdf</name> </xyz_1> <xyz_2> <c_name>chart1.gif</c_name> </xyz_2> </tag> </tags>
the wanted, correct result produced:
<tags> <tag> <tag1>tagname1</tag1> </tag> </tags>
explanation:
the identity rule (unless overriden) copies every node as-is
the overriding template matching elements
name()
starts-with()
"xyz_" , template has empty body -- deletes matched element output.the
<xsl:strip-space elements="*"/>
directive instructs xslt processor parse xml document ignoring whitespace-only text node in document. no whitespace-only node seen transformation hence no such nodes copied output. eliminates unwanted whitespace, reported second problem.
Comments
Post a Comment