Removing Elements from an XML Document, XSLT, and JAXB

This question is a continuation of my previous question: Creating a valid XSD open using <all> and <any> Elements

Given that I have a Java string containing an XML document of the following form:

<TRADE> <TIME>12:12</TIME> <MJELLO>12345</MJELLO> <OPTIONAL>12:12</OPTIONAL> <DATE>25-10-2011</DATE> <HELLO>hello should be ignored</HELLO> </TRADE> 

How to use XSLT or the like (in Java using JAXB) to remove all elements not contained in a set of elements. In the above example, I'm only interested in (TIME, OPTIONAL, DATE), so I would like to convert it to:

 <TRADE> <TIME>12:12</TIME> <OPTIONAL>12:12</OPTIONAL> <DATE>25-10-2011</DATE> </TRADE> 

The order of the elements is not fixed.

+4
source share
3 answers

This conversion is:

 <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:param name="pNames" select="'|TIME|OPTIONAL|DATE|'"/> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="node()|@*" name="identity"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="*/*"> <xsl:if test="contains($pNames, concat('|', name(), '|'))"> <xsl:call-template name="identity"/> </xsl:if> </xsl:template> </xsl:stylesheet> 

when applied to the provided XML document:

 <TRADE> <TIME>12:12</TIME> <MJELLO>12345</MJELLO> <OPTIONAL>12:12</OPTIONAL> <DATE>25-10-2011</DATE> <HELLO>hello should be ignored</HELLO> </TRADE> 

creates the desired, correct result:

 <TRADE> <TIME>12:12</TIME> <OPTIONAL>12:12</OPTIONAL> <DATE>25-10-2011</DATE> </TRADE> 

Explanation

  • An identity rule (template) copies each node "as is".

  • An identification rule is overridden by a template that matches any element that is not the top element of the document . Inside the template, a check is performed if the name of the matching element is one of the names specified in the external parameter $pNames in the line of dereferenced lines with null names.

  • Refer to your XSLT processor documentation on how to pass a parameter to a conversion - this is implementation dependent and differs from processor to processor.

+6
source

I haven't tried it yet, but maybe the javax.xml.tranform package might help:

http://download.oracle.com/javase/6/docs/api/javax/xml/transform/package-summary.html

+1
source

JAXB and XSLT

JAXB integrates very well with XSLT for example:

Another question

According to your previous question (see link below), the conversion is really not necessary, because JAXB will simply ignore attributes and elements that do not appear in fields / properties in the domain object.

+1
source

Source: https://habr.com/ru/post/1342123/


All Articles