简体   繁体   中英

How to add multiple node in xml using java

I want to create an xml file like this:

  <Record Number="001">
    <RefNum></RefNum>
    <TrackRef></TrackRef>
  <Record>
</Batch>

How can i create element Record Number with spaces in between and how to give its value as "001"?

You can use a DocumentBuilder for creating this xml.

Please see some sample code below:

 DocumentBuilderFactory dbFactory =
 DocumentBuilderFactory.newInstance();
 DocumentBuilder dBuilder = 
    dbFactory.newDocumentBuilder();
 Document doc = dBuilder.newDocument();
 // root element
 Element rootElement = doc.createElement("");

Then output the result in XML file as as shown below :

// write the content into xml file
 TransformerFactory transformerFactory =
 TransformerFactory.newInstance();
 Transformer transformer =
 transformerFactory.newTransformer();
 DOMSource source = new DOMSource(doc);
 StreamResult result =
 new StreamResult(new File("C:\\test.xml"));
 transformer.transform(source, result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM