2017-01-17 3 views
0

В приведенном ниже примере, когда мы входим в метод writeOneMoreElement() и возникает Exception, как получить доступ к предыдущим данным, которые мы пишем на XML. Здесь мы теряем каждую запись, если исключение происходит в методе writeOneMoreElement().при написании XML с помощью анализатора stax, если в моем собственном методе возникает исключение, как сохранить или получить доступ к предыдущим данным.

public class xmlSample { 
    public static void main(String[] args) { 
    XMLOutputFactory factory = XMLOutputFactory.newInstance(); 
    try { 

     XMLStreamWriter writer1 = factory.createXMLStreamWriter(new FileWriter("E:\\sampleXML.xml")); 
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 
     XMLOutputFactory xmlOutputFactory = new WstxOutputFactory(); 
     XMLStreamWriter2 xtw = (XMLStreamWriter2) new WstxOutputFactory() 
       .createXMLStreamWriter(byteArrayOutputStream, "UTF-8"); 

     xtw.writeStartDocument("UTF-8", "1.1"); 
     xtw.setPrefix("itm", "http://adt.cmn.xmlns.commons.platform.actiance.com/core/1.0"); 

     xtw.writeStartElement("document"); 
     xtw.writeStartElement("data1"); 
     xtw.writeCharacters("Sagar"); 
     xtw.writeEndElement(); 

     XMLStreamWriter2 writer2 = writeOneMoreElement(xtw); 

     writer2.writeStartElement("data2"); 
     writer2.writeCharacters("Shubham"); 
     writer2.writeEndElement(); 

     writeOneMoreElement(writer2); 

     writer2.writeEndDocument(); 
     writer2.close(); 
     xtw.flush(); 
     xtw.close(); 

     System.out.println("XML :" + new String(byteArrayOutputStream.toByteArray())); 

    } catch (XMLStreamException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

} 

private static XMLStreamWriter2 writeOneMoreElement(XMLStreamWriter2 writer2) 
     throws XMLStreamException, IOException { 

    try { 
     writer2.writeStartElement("ABC"); 
     writer2.writeStartElement("data2"); 
     writer2.writeAttribute("name2", "value2"); 
     writer2.writeAttribute("otherAttribute", "true"); 
     writer2.writeEndElement(); 

     writer2.writeStartElement("data3"); 
     writer2.writeAttribute("name3", "value3"); 
     writer2.writeAttribute("otherAttribute", "true"); 
     writer2.writeEndElement(); 

     writer2.writeEndElement(); 

     writer2.flush(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return writer2; 
} 
} 
+0

Привет, пожалуйста, примите ответ, если вы нашли это полезным, или комментарий, почему это не было полезно. Это поможет всем остальным разработчикам, читающим это в будущем. – Ray

ответ

0

Одно из правил исключений является то, что в зависимости от того строки генерирует исключение, все строки, после этого не будут выполняться, пока не достигнут catch и finally блоков. Таким образом, эта строка System.out.println("XML :" + new String(byteArrayOutputStream.toByteArray())); никогда не выполняется, но значения все еще доступны в byteArrayOutputStream до завершения программы.

Одним из возможных решений является запуск такого же метода println() в блоке catch. Как так:

public static void main(String[] args) { 
    XMLOutputFactory factory = XMLOutputFactory.newInstance(); 
    //Initializing the ByteArrayOutputStream outside the try block, so that it is still available after that scope. 
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 
    try { 

     XMLStreamWriter writer1 = factory.createXMLStreamWriter(new FileWriter("E:\\sampleXML.xml")); 
     //ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 
     XMLOutputFactory xmlOutputFactory = new WstxOutputFactory(); 
     XMLStreamWriter2 xtw = (XMLStreamWriter2) new WstxOutputFactory() 
       .createXMLStreamWriter(byteArrayOutputStream, "UTF-8"); 

     xtw.writeStartDocument("UTF-8", "1.1"); 
     xtw.setPrefix("itm", "http://adt.cmn.xmlns.commons.platform.actiance.com/core/1.0"); 

     xtw.writeStartElement("document"); 
     xtw.writeStartElement("data1"); 
     xtw.writeCharacters("Sagar"); 
     xtw.writeEndElement(); 

     XMLStreamWriter2 writer2 = writeOneMoreElement(xtw); 

     writer2.writeStartElement("data2"); 
     writer2.writeCharacters("Shubham"); 
     writer2.writeEndElement(); 

     //Exception thrown here 
     writeOneMoreElement(writer2); 

     //Unexecuted code from here onwards 
     writer2.writeEndDocument(); 
     writer2.close(); 
     xtw.flush(); 
     xtw.close(); 

     System.out.println("XML :" + new String(byteArrayOutputStream.toByteArray())); 

    } catch (XMLStreamException e) { 
     e.printStackTrace(); 
     /*Proof of concept. This line will print out all the values inserted into the ByteArrayOutputStream up to 
     the point where the Exception was thrown.*/ 
     System.out.println("XML :" + new String(byteArrayOutputStream.toByteArray())); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

} 

private static XMLStreamWriter2 writeOneMoreElement(XMLStreamWriter2 writer2) 
     throws XMLStreamException/*, IOException*/ { 
    //By the way, why does this method throw IOException? It's unnecessary, and you can remove it. 
    try { 
     writer2.writeStartElement("ABC"); 
     writer2.writeStartElement("data2"); 
     writer2.writeAttribute("name2", "value2"); 
     writer2.writeAttribute("otherAttribute", "true"); 
     writer2.writeEndElement(); 

     writer2.writeStartElement("data3"); 
     writer2.writeAttribute("name3", "value3"); 
     writer2.writeAttribute("otherAttribute", "true"); 
     writer2.writeEndElement(); 

     writer2.writeEndElement(); 

     writer2.flush(); 
     //I'm throwing an Exception here on purpose to trigger the catch block. 
     throw new XMLStreamException(); 
    }  
    catch (Exception e) { 
     e.printStackTrace(); 
     // I'm rethrowing the Exception on purpose. 
     throw e; 
    } 
    //This line won't work for now, but you can change it back. 
    //return writer2; 
} 

Запустите программу, и вы получите ожидаемый XMLStreamException, а также неполные данные.

XML :<?xml version='1.1' encoding='UTF-8'?><document><data1>Sagar</data1><ABC><data2 name2="value2" otherAttribute="true" /><data3 name3="value3" otherAttribute="true" /></ABC>

Смежные вопросы