更好的方法在java中创建一个xml

时间:2015-05-26 10:36:29

标签: java xml

我正在通过dom解析器创建xml,如下面的方法中所示请提示是否有任何其他更好的方法在java中实现相同,因为dom解析器被认为是加载内存,为什么我在寻找更好的方法

String xmlString = null ;  
        try {

            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            Document doc = docBuilder.newDocument();

            DOMSource source = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            SimpleDateFormat dateformatyyyyMMdd = new SimpleDateFormat("yyyyMMdd");



            Element rootElement = doc.createElement("abcmail");
            doc.appendChild(rootElement);



            Element invoiceReferenceNotificationMessage = doc.createElement("invoiceReferenceNotificationMessage");
            rootElement.appendChild(invoiceReferenceNotificationMessage);


            Element ceReference = doc.createElement("ceReference");
            ceReference.appendChild(doc.createTextNode(irm.getceReference()));
            ceReferenceNotificationMessage.appendChild(ceReference);


            Element RBSReference = doc.createElement("ABSReference");
            ABSReference.appendChild(doc.createTextNode(irm.getABSReference()));
            ceReferenceNotificationMessage.appendChild(ABSReference);


            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();

            transformer.transform(source, result);
            writer.flush();
            xmlString = writer.toString();

            return xmlString;

          } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
          } catch (TransformerException tfe) {
            tfe.printStackTrace();
          }
        return xmlString;

    }

1 个答案:

答案 0 :(得分:1)

更好的方法是使用JAXB。

您可以看到示例here