For such a need, I would explicitly suggest XSLT , since XML transformation and XSLT were created to transform the XML content.
Then i used a template style sheets intended for use as a string format as follows:
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'> <xsl:template match='/'> <elements> <xsl:apply-templates select="elements/element1" mode="%s"/> <xsl:apply-templates select="elements/element2" mode="%s"/> <xsl:apply-templates select="elements/element3" mode="%s"/> <xsl:apply-templates select="elements/element4" mode="%s"/> <xsl:apply-templates select="elements/element5" mode="%s"/> </elements> </xsl:template> <xsl:template match='*' mode='normal'> <xsl:copy-of select="."/> </xsl:template> <xsl:template match='*' mode='comment'> <xsl:text disable-output-escaping="yes"><!--</xsl:text><xsl:copy-of select="."/>--<xsl:text disable-output-escaping="yes">></xsl:text> </xsl:template> </xsl:stylesheet>
As you can see, there are 2 modes:
- if you select
normal , it will just copy the contents of node - if you select
comment , he will comment on his content
So, if we activate element1 , element3 and element5 , the real content of our stylesheet will be String.format(template, "normal", "comment", "normal", "comment", "normal")
In the code snippet below, I use jcabi-xml as it is very easy to use, but you can use a different library if you wish, XSLT is the standard, so it will work anyway.
XML first = new XMLDocument( "<elements>\n" + " <element1 atribute=\"value\"/>\n" + " <element2 atribute=\"value\"/>\n" + " <element3 atribute=\"value\"/>\n" + " <element4 atribute=\"value\"/>\n" + " <element5 atribute=\"value\"/>\n" + "</elements>" ); String template = "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" + " <xsl:template match='/'>\n" + " <elements>\n" + " <xsl:apply-templates select=\"elements/element1\" mode=\"%s\"/>\n" + " <xsl:apply-templates select=\"elements/element2\" mode=\"%s\"/>\n" + " <xsl:apply-templates select=\"elements/element3\" mode=\"%s\"/>\n" + " <xsl:apply-templates select=\"elements/element4\" mode=\"%s\"/>\n" + " <xsl:apply-templates select=\"elements/element5\" mode=\"%s\"/>\n" + " </elements>\n" + " </xsl:template>\n" + " <xsl:template match='*' mode='normal'>\n" + " <xsl:copy-of select=\".\"/>\n" + " </xsl:template>\n" + " <xsl:template match='*' mode='comment'>\n" + " <xsl:text disable-output-escaping=\"yes\"><!--</xsl:text><xsl:copy-of select=\".\"/>--<xsl:text disable-output-escaping=\"yes\">></xsl:text>\n" + " </xsl:template>\n" + "</xsl:stylesheet>"; XML second = new XSLDocument( String.format(template, "normal", "comment", "normal", "comment", "normal") ).transform(first); System.out.println(second.toString());
Output:
<?xml version="1.0" encoding="UTF-8"?> <elements> <element1 atribute="value"/> <element3 atribute="value"/> <element5 atribute="value"/> </elements>
NB:. For readability, I formatted the output
Nicolas filotto
source share