gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:10:41 26 4
gpt4 key购买 nike

我有以下程序,我试图在其中生成一个 XML,该 XML 也是通过 DOM 解析器生成的。我想将生成的 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();
}

}}

最佳答案

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

        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();

关于java - 将生成的xml存储到java中的字符串变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30425336/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com