Inheritance
Getting started with Java
Streams
Exceptions
Collections
Lambda Expressions
Generics
File I/O
Arrays
Interfaces
Maps
Strings
InputStreams and OutputStreams
Default Methods
Classes and Objects
Basic Control structures
Concurrent Programming Threads
Console I/O
Singletons
Visibility controlling access to members of a class
Regular Expressions
Autoboxing
Documenting Java Code
Executor, ExecutorService and Thread pools
Object Class Methods and Constructor
JAXB
Primitive Data Types
Networking
Optional
Enums
HttpURLConnection
Annotations
Audio
Data Class
Calendar and its Subclasses
Nashorn JavaScript engine
Java Native Interface (JNI)
Remote Method Invocation (RMI)
Iterator and Iterable
Operators
Asserting
Scanner
Properties Class
Preferences
Reflection API
Constructors
ByteBuffer
Serialization
JSON in Java
Random Number Generation
Recursion
Polymorphism
StringBuilder
Refernce Data Types
Bit Manipulation
Java Agents
Encapsulation
Type Conversion
BigInteger
BigDecimal
RSA Encryption
Varargs Variable Arguments
ThreadLocal
Logging
static keyword
Disassembling and Decompling
Resources on classpath
log4j, log4j2
JVM Flags
Oracle Official Code Standard
Character encoding
Java Memory Management
Immutable Objects
Object Cloning
Alternative Collections
Lists
BufferedWriter
LocalTime
Sets
Comparable and Comparator
JVM Tool Interface
Nested and Inner Classes
Apache Commons Lang
Getters and Setter
The Classpath
Bytecode Modification
XML Parsing using JAXP
Reference Types
Localization and Internationalization
JAX-WS
XML XPath Evaluation
Performance Tuning
Parallel programming with ForkJoin framework
Common Pitfalls
Non-Access Modifiers
Java Compiler
XJC
Installing Java Standard Edition
Process
Command line argument processing
Dates and Time using java.time
Fluent Interface
XOM - XML Object Model
XOM - XML Object Model
Reading a XML file
Writing to a XML File
Just in Time JIT compiler
FTP File Transfer Protocol
Java Native Access JNI
Modules
Pitfalls - exceptions
Pitfalls - language syntax
ServiceLoader
ClasssLoader
Object References
Pitfalss - performance
Creating Images Programmatically
Applets
NIO Networking
New File I/O
Secure objects
Pitfalls - threads and concurrency
Splitting a string into fixed length parts
Pitfalls - nulls and NullPointerException
SecurityManager
JNDI
super keyword
java.util.Objects class
Java command: java and javaw
Atomic types
Floating Point Operations
Converting to and from strings
sun.misc.Unsafe
Java Memory Model
Java deployment
Java plugin system implementations
Queues and deques
Runtime commands
NumberFormat
Security and Cryptograhy
Java Virtual Machine JVM
Unit Testing
JavaBean
Expressions
Literals
Java SE 8 Features
Java SE 7 Features
Packages
Concurrency and Money
Concurrent Collections
Using ThreadPoolExecutor in multi-threaded applications
Java Editions, versions, releases and distributions
Dynamic method dispatch
JMX
Security and cryptography
Generating Java Code
JShell
Benchmarks
Collection Factory Methods
Multi-release JAR files
Stack-Walking API
TreeMap and TreeSet
Sockets
Java Sockets
Using other scripting languages in Java
Functional interfaces
List vs. set
2D graphics
Reflection
Deque interface
Enum Map
EnumSet class
Local Inner class
Java Print Service
Immutable class
String Tokenizer
File upload to S3 / AWS
Readers and writers
Hashtable
Enum starting with a number
SortedMap
WeakHashMap
LinkedHashMap
StringBuffer
Choosing Collections
C++ Comparison
CompletableFuture
Contributors

Writing to a XML File

suggest change

Writing to a XML File using XOM is very similar to reading it except in this case we are making the instances instead of retrieving them off the root.

To make a new Element use the constructor Element(String name). You will want to make a root element so that you can easily add it to a Document.

Element root = new Element("root");

The Element class has some handy methods for editing elements. They are listed below:

The Attribute class has a couple of different constructors. The simplest one is Attribute(String name, String value).


Once you have all of your elements add to your root element you can turn it into a Document. Document will take a Element as an argument in it’s constructor.

You can use a Serializer to write your XML to a file. You will need to make a new output stream to parse in the constructor of Serializer.

FileOutputStream fileOutputStream = new FileOutputStream(file);
Serializer serializer = new Serializer(fileOutputStream, "UTF-8");
serializer.setIndent(4);
serializer.write(doc);

Example

Code:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import nu.xom.Attribute;
import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Elements;
import nu.xom.ParsingException;
import nu.xom.Serializer;

public class XMLWriter{
    
    public static void main(String[] args) throws UnsupportedEncodingException, 
            IOException{
        // root element <example>
        Element root = new Element("example");
        
        // make a array of people to store
        Person[] people = {new Person("Smith", "Dan", "years", "green", 23), 
            new Person("Autry", "Bob", "months", "N/A", 3)};
        
        // add all the people
        for (Person person : people){
            
            // make the main person element <person>
            Element personElement = new Element("person");
            
            // make the name element and it's children: first and last
            Element nameElement = new Element("name");
            Element firstNameElement = new Element("first");
            Element lastNameElement = new Element("last");
            
            // make age element
            Element ageElement = new Element("age");
            
            // make favorite color element
            Element favColorElement = new Element("fav_color");
            
            // add value to names
            firstNameElement.appendChild(person.getFirstName());
            lastNameElement.appendChild(person.getLastName());
            
            // add names to name
            nameElement.appendChild(firstNameElement);
            nameElement.appendChild(lastNameElement);
            
            // add value to age
            ageElement.appendChild(String.valueOf(person.getAge()));
            
            // add unit attribute to age
            ageElement.addAttribute(new Attribute("unit", person.getAgeUnit()));
            
            // add value to favColor
            favColorElement.appendChild(person.getFavoriteColor());
            
            // add all contents to person
            personElement.appendChild(nameElement);
            personElement.appendChild(ageElement);
            personElement.appendChild(favColorElement);
            
            // add person to root
            root.appendChild(personElement);
        }
        
        // create doc off of root
        Document doc = new Document(root);
        
        // the file it will be stored in
        File file = new File("out.xml");
        if (!file.exists()){
            file.createNewFile();
        }
        
        // get a file output stream ready
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        
        // use the serializer class to write it all
        Serializer serializer = new Serializer(fileOutputStream, "UTF-8");
        serializer.setIndent(4);
        serializer.write(doc);
    }

    private static class Person {

        private String lName, fName, ageUnit, favColor;
        private int age;

        public Person(String lName, String fName, String ageUnit, String favColor, int age){
            this.lName = lName;
            this.fName = fName;
            this.age = age;
            this.ageUnit = ageUnit;
            this.favColor = favColor;
        }

        public String getLastName() { return lName; }
        public String getFirstName() { return fName; }
        public String getAgeUnit() { return ageUnit; }
        public String getFavoriteColor() { return favColor; }
        public int getAge() { return age; }
    }
    
}

This will be the contents of “out.xml”:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents
11 Maps
26 JAXB
30 Enums
33 Audio
76 Lists
79 Sets
90 JAX-WS
97 XJC
107 Modules
115 Applets
123 JNDI
151 JMX
154 JShell
160 Sockets