Create New Xml File and Write Data to It

Create new XML file and write data to it?

DOMDocument is a great choice. It's a module specifically designed for creating and manipulating XML documents. You can create a document from scratch, or open existing documents (or strings) and navigate and modify their structures.

$xml = new DOMDocument();
$xml_album = $xml->createElement("Album");
$xml_track = $xml->createElement("Track");
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );


To re-open and write:

$xml = new DOMDocument();
$nodes = $xml->getElementsByTagName('Album') ;
if ($nodes->length > 0) {
//insert some stuff using appendChild()


Java creating a new xml file and appending it

I simulated your code here and did realized the you are not creating a valid root element in XML file, that's why you getting the exception.

See my results that I am getting running the write method:

public static void main(String... x) {
Sentence s = new Sentence();
Main m = new Main();
List<Sentence> list = new ArrayList<Sentence>();

Sentence class:

public class Sentence {
public String[] getWordList() {
return new String[] { "w4", "w5", "w6" }; // previous: w1,w2,w3


<?xml version="1.0" encoding="UTF-8" standalone="no"?>

Just replace your code with the following:

// text element
Element rootElement = null;
if (!fileExist) {
rootElement = doc.createElement("text");
} else {
rootElement = doc.getDocumentElement(); // get the root [text] element

Create write and save xml file dynamically in c# .net

Two thing:

  1. Please post correct code. The XDocument class has no instance method
    "parse", only "Parse". The XDocument class has no instance method
    "Load", only static method "Load".
  2. xdoc.Parse(content) would create
    a XDocument from the string. XDocument.Load(filename) would return a
    XDocument loaded from the XML file "filename".

This would do the job:

foreach(DataRow dr in dt.Rows) {
string filepath = ConfigurationManager.Appsetings[Constants.FailedDocuments];
string filename = "message_"+ dr["documentId"].ToString();
string content = dr["documentContent"].ToString();
XDocument xdoc = new XDocument();

Write an XML file through a C program

The problem appears to be in your function call:


This way, for each iteration, you're essentially accessing the first element m[0] in the function call.

You want to pass the address of each individual elements in the array, like


or, to simplify, you can pass the element itself (not the address), like


and change the function like

void output(FILE *f, Measurement x){ // second argument is not a pointer
fprintf(f,"<minimum>%f</minimum>\n",x.minimum); // x is not a pointer
fprintf(f,"<maximum>%f</maximum>\n",x.maximum); .....

That said, the scan statements


should be


as daynumber is of type int, and for the others


should be


as minimum and other members are of type double.

How do I create individual XML files from the parsed data output of a XML file?

Just use the File I/O APIs as usual to create your xml files within the loop.

// for every Node in the template List
for(int i=0; i < templateList.getLength(); i++) {

// cast each Node to a template Element
Node theTemplate = templateList.item(i);
Element templateElement = (Element) theTemplate;

// get the xml filename as = template's name attribute + .xml
String fileName = templateElement.getAttribute("name") + ".xml";

// create a Path that points to the current directory
Path filePath = Paths.get(fileName);

// create the xml file at the specified Path

System.out.println("File "+ fileName + ".xml created");

The above code would create the xml files in your current working directory. You'll need to handle the checked IOException too.

Generate XML document in R

Might be easily solveable w/out any of those packages... if your structure is fairly static, I would use and then just cat() the file out. Something like this:

## I guess your data looks like this?
df <- data.frame(number = c(1,2),
uri = c("<",
plugin = c("class",
"class org.esa.s2tbx.dataio.s2.ortho.plugins.Sentinel2L1CProduct_Multi_UTM42N_ReaderPlugIn"))

## build a function that outputs every block in xml format
thingieBuilder <- function(number, uri, plugin){

## now run that for each entry in your df and unlist it, and make it a sausage, seperated by newlines
xmlProducts <- df %>% purrr::pmap(thingieBuilder) %>% unlist %>% paste(collapse = "\n")

## Now stick on top and bottom, and cat it to a file!
</session>") %>%
cat(file = "boom.xml")

How to create XML file using Python?

You need to

  1. Use ET.tostring() to get your xml as a string
  2. Use xml.dom.minidom to get a DOM object from the string
  3. Use toprettyxml() of DOM object to get the xml as formatted string
  4. Add encoding information to the xml declaration part by simply splitting and concating the formatted string
  5. Write the string to a file


import xml.etree.cElementTree as ET
import xml.dom.minidom

m_encoding = 'UTF-8'

root = ET.Element("data")
doc = ET.SubElement(root, "status", date="20210123")
ET.SubElement(doc, "name", name="john").text = "some value1"
ET.SubElement(doc, "class", name="abc").text = "some vlaue2"

dom = xml.dom.minidom.parseString(ET.tostring(root))
xml_string = dom.toprettyxml()
part1, part2 = xml_string.split('?>')

with open("FILE.xml", 'w') as xfile:
xfile.write(part1 + 'encoding=\"{}\"?>\n'.format(m_encoding) + part2)

Output file

<?xml version="1.0" encoding="UTF-8"?>

<status date="20210123">
<name name="john">some value1</name>
<class name="abc">some vlaue2</class>

Related Topics

Leave a reply