Создание XML файла на Java
Решение
Для создания XML файла сначала создадим пустой XML документ с помощью DOM анализатора (парсера).
В приведенном примере XML документ создатся с помощью объекта javax.xml.parsers.DocumentBuilder , который мы получаем из фабрики javax.xml.parsers.DocumentBuilderFactory . Дополнительно у фабрики включаем поддержку пространства имен с помощью метода setNamespaceAware для работы с XML-схемой(XSD) вместо устаревшго объявления типов документа DTD.
Добавим в XML документ корневой элемент, для примера назовем его root. Далее в корневой элемент добавим дочерние элементы, в нашем примере они называются item
В основе работы с деревом DOM лежит объект элемента (интерфейс org.w3c.dom.Element ), к которому мы можем добавлять дочерние элементы через метод appendChild или устанавливать атрибуты посредством метода setAttribute.
Далее необходимо созданный XML документ записать в файл. Для этого используется класс javax.xml.transform.Transformer, который создается с помощью фабрики javax.xml.transform.TransformerFactory
В приведенном примере, создается файл для записи, после чего с помощью метода трансформера transform записываются данные в файл.
How to write XML file in Java – (DOM Parser)
This tutorial shows how to use the Java built-in DOM APIs to write data to an XML file.
Table of contents
P.S Tested with Java 11
1. Write XML to a file
Steps to create and write XML to a file.
- Create a Document doc .
- Create XML elements, attributes, etc., and append to the Document doc .
- Create a Transformer to write the Document doc to an OutputStream .
2. Pretty Print XML
2.1 By default, the Transformer outputs the XML in a compact format.
2.2 We can set the OutputKeys.INDENT in Transformer to enable the pretty print format.
3. Write XML elements, attributes, comments CDATA, etc
The below example uses a DOM parser to create and write XML to an OutputStream .
4. DOM FAQs
Some DOM parser commonly asked questions.
4.1 How to disable the XML declaration?
We can configure the OutputKeys.OMIT_XML_DECLARATION to disblae the XML declaration.
4.2 How to change the XML encoding?
We can configure the OutputKeys.ENCODING to change the XML encoding.
4.3 How to pretty-print the XML?
We can configure the OutputKeys.INDENT to enable the pretty print XML.
4.4 How to hide the XML declaration `standalone=”no”`?
We can configure the document.setXmlStandalone(true) to hide the XML declaration standalone="no" .
4.5 How to change the XML declaration version?
We can configure the document.setXmlVersion("version") to change the XML declaration version.
5. Download Source Code
6. References
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.
Comments
Thanks man!, you did a great job!
thanks a lot for the code to write to XML. Helped me a lot.
I found that FileOutputStream needs to be closed after writing to XML i.e., output.close(); Without closing this, I encountered issues when processing this file further.
Thanks! This totally got me out of the water.
Thanks for this code. I have a for loop of 100 times, where 5 xml elements are being formed for each. So, the expected output is to have a XML file with 100 blocks (5 elements each). Currently, the last for loop’s content is being stored and showing just 1 block in XML. Can you help how can I put the blocks into same XML?
Create XML file using java
How to create a xml file and save it in some place in my machine using java..there are attributes also include in the xml file? I have found org.w3c.dom.Document but having problems with creating attributes for elements and save the xml file.
8 Answers 8
You can use a DOM XML parser to create an XML file using Java. A good example can be found on this site:
![]()
You can use Xembly, a small open source library that makes this XML creating process much more intuitive:
Xembly is a wrapper around native Java DOM, and is a very lightweight library (I’m the author).
Have look at dom4j or jdom. Both libraries allow creating a Document and allow printing the document as xml. Both are widly used, pretty easy to use and you’ll find a lot of examples and snippets.
Just happened to work at this also, use https://www.tutorialspoint.com/java_xml/java_dom_create_document.htm the example from here, and read the explanations. Also I provide you my own example:
This is in the context of using the tokenizer from Stanford for Natural Language Processing, just a part of it to make an idea on how to add elements. The output is: Billbuyedapples (I’ve read the sentence from a file)
![]()
I am providing an answer from my own blog. Hope this will help.
What will be output?
Following XML file named users.xml will be created.
PROCEDURE
Basic steps, in order to create an XML File with a DOM Parser, are:
Create a DocumentBuilder instance.
Create a Document from the above DocumentBuilder .
Create the elements you want using the Element class and its appendChild method.
Как создать XML-файл в Java — (DOM Parser)
DOM предоставляет множество удобных классов для простого создания XML-файла. Во-первых, вы должны создать документ с классомDocumentBuilder, определить все содержимое XML — узел, атрибут с классомElement. Наконец, используйте классTransformer для вывода всего содержимого XML в поток вывода, обычно это файл.
В этом руководстве мы покажем вам, как использовать DOM XML-парсер для создания XML-файла.
Пример DOM Parser
В конце примера будет создан следующий XML-файл с именем «file.xml».
File : WriteXMLFile.java — Java-класс для создания XML-файла.
Новый файл XML создается в «C:\file.xml» с кодировкой по умолчанию UTF-8.
Note
Для отладки вы можете изменитьStreamResult для вывода содержимого XML на консоль.