将生成的xml存储到java中的字符串变量中

时间:2015-05-24 15:43:01

标签: java dom

我有以下程序,我正在尝试生成一个也通过DOM解析器生成的XML。我想将生成的XML存储到字符串变量中,但它无法正常工作。

如何将生成的XML存储到字符串变量中?

public class generatexml {

    public static void main(String[] args) {


        //************ wantt to store the generated xml in a string ********
        String s = generatexml();

    }

    public static StreamResult generatexml()
    {
          try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            // root elements
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("kermail");
            doc.appendChild(rootElement);

            for(int i =0 ;i<5 ;i++ )

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

            Element InvoiceReference = doc.createElement("abceReference");
            InvoiceReference.appendChild(doc.createTextNode("7815"));
            invoiceReferenceNotificationMessage.appendChild(abceReference);
        }


            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);

             StreamResult result = new StreamResult(System.out);
            transformer.transform(source, result);

            return result;

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

        }}

1 个答案:

答案 0 :(得分:1)

您的代码对我来说似乎是正确的。但看起来你需要做

        transformer.transform(source, result);
        System.out.println();
        return result;

Is there a more elegant way to convert an XML Document to a String in Java than this code?

描述了其他方式

更新: -

      DOMSource source = new DOMSource(doc);
       StringWriter writer = new StringWriter();
       StreamResult result = new StreamResult(writer);
       TransformerFactory tf = TransformerFactory.newInstance();
       Transformer transformer = tf.newTransformer();
       transformer.transform(source , result);
       writer.flush();
       String xmlString = writer.toString();