I'm trying to cut a xml into parts and then apply it some transformations. Currently I have this code:
public class XMLStax_xslt {
static boolean allowStream = false;
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("SourceExternalFile.xml");
XMLInputFactory xmlif = null;
xmlif = XMLInputFactory.newInstance();
Source xslt = new StreamSource(new File("myTransformFile.xslt"));
StreamFilter filter = new StreamFilter() {
@Override
public boolean accept(XMLStreamReader reader) {
int eventType = reader.getEventType();
if ( eventType == XMLEvent.START_ELEMENT )
{
String currentTag = reader.getLocalName();
if (currentTag.equals("wantedTag"))
{
allowStream = true;
}
}
if ( eventType == XMLEvent.END_ELEMENT )
{
String currentTag = reader.getLocalName();
if (currentTag.equals("wantedTag"))
{
allowStream = false;
}
}
return allowStream;
}
};
XMLStreamReader xmlR = xmlif.createFilteredReader(xmlif.createXMLStreamReader(fis),filter);
while (xmlR.hasNext())
{
TransformerFactory transformerXSLT = TransformerFactory.newInstance();
Transformer currentXslt = transformerXSLT.newTransformer(xslt);
currentXslt.transform(new StAXSource(xmlR), new StreamResult("targetFile.xml"));
}
fis.close();
}
}
Which works when the line return allowStream;
is changed to return true;
. So, what I need is send only the part I need to the transformation because sending the whole XML is not an option.
How can I achieve that?
Thanks.
The trouble was that I was passing the string to the transformer, instead of the whole node. Changing XMLStreamReader
by XMLEventReader
does the trick.
Here's the change:
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("SourceExternalFile.xml");
XMLInputFactory xmlif = null;
xmlif = XMLInputFactory.newInstance();
Source xslt = new StreamSource(new File("myTransformFile.xslt"));
XMLEventReader xmlR = xmlif.createXMLEventReader(xmlif.createXMLStreamReader(fis));
TransformerFactory transformerXSLT = TransformerFactory.newInstance();
Transformer currentXslt = transformerXSLT.newTransformer(xslt);
while (xmlR.hasNext())
{
XMLEvent xmlEvent = xmlR.nextEvent();
if ( xmlEvent.equals("wantedTag") )
{
currentXslt.transform(new StAXSource(xmlR), new StreamResult("targetFile.xml"));
}
}
xmlR.close();
fis.close();
}