我试图将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不是一个选项。
我怎样才能做到这一点?
感谢。
答案 0 :(得分:0)
麻烦的是我将字符串传递给变换器,而不是整个节点。将XMLStreamReader
改为XMLEventReader
可以解决问题。
这是改变:
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();
}