用Java写入XML文件

我正在处理以下代码:

import java.io.*;

import javax.xml.parsers.*;

import javax.xml.transform.*;

import javax.xml.transform.dom.*;

import javax.xml.transform.stream.*;

import org.w3c.dom.*;

public class CreatXMLFile {

public static void main(String[] args) throws Exception {

BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

// System.out.print("Enter number to add elements in your XML file: ");

// String str = bf.readLine();

int no=2;

// System.out.print("Enter root: ");

String root = "SMS";

DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance();

DocumentBuilder documentBuilder =documentBuilderFactory.newDocumentBuilder();

Document document = documentBuilder.newDocument();

Element rootElement = document.createElement(root);

document.appendChild(rootElement);

// for (int i = 1; i <= no; i++)

// System.out.print("Enter the element: ");

// String element = bf.readLine();

String element ="Number";

System.out.print("Enter the Number: ");

String data = bf.readLine();

Element em = document.createElement(element);

em.appendChild(document.createTextNode(data));

rootElement.appendChild(em);

String element1 ="message";

System.out.print("Enter the SMS: ");

String data1 = bf.readLine();

Element em1 = document.createElement(element1);

em1.appendChild(document.createTextNode(data1));

rootElement.appendChild(em1);

TransformerFactory transformerFactory = TransformerFactory.newInstance();

Transformer transformer = transformerFactory.newTransformer();

DOMSource source = new DOMSource(document);

StreamResult result = new StreamResult(System.out);

transformer.transform(source, result);

}

}

它给出以下输出:

run:

Enter the Number: 768678

Enter the SMS: ytu

<?xml version="1.0" encoding="UTF-8" standalone="no"?><SMS><Number>768678</Number><message>ytu</message></SMS>BUILD SUCCESSFUL (total time: 8 seconds)

现在,我想将生成的输出(<?xml version="1.0" encoding="UTF-8"

standalone="no"?><SMS><Number>768678</Number><message>ytu</message></SMS>)写入硬盘上的XML文件。我该怎么做?

回答:

使用FileOutputStream(或File)代替System.out构造您的StreamResult

以上是 用Java写入XML文件 的全部内容, 来源链接: utcz.com/qa/420313.html

回到顶部