我正在尝试将 xml 切割成多个部分,然后对其进行一些转换。目前我有这个代码:
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();
}
}
当线路return allowStream;
更改为return true;
. 所以,我需要的只是将我需要的部分发送到转换,因为发送整个 XML 不是一种选择。
我怎样才能做到这一点?
谢谢。