code.dreamsense.com

Writing XML

So, what is XML? XML stands for eXtensible Markup Langugage.

It was the basic goto for transferring data in a format specified by onne party and used by others. There's no spcific way that an XML file should look, only that it needs to be well formatted.

What's a well formatted XML document look like? Well, here's an example.

  <?xml version="1.0"?>
  <data>
    <firstName>John</firstName>
    <lastName>Smith</lastName>
    <phone>916-555-4418</phone>
  </data>

There ya go, that's a well formatted XML document. As you can see, each node has a starting and a matching end node. Simple enough right?

You can make any kind of data document using XML. For example, let's say you wanted files sent in a specific format, you could use XML as that goto. grabbing data in this way, you can ensure that you get what you need.

If we wanted to output the above xml, we could use Java and the XMLStreamWriter class.

  import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.util.HashMap;
  import java.util.Map;

  import javax.xml.stream.XMLOutputFactory;
  import javax.xml.stream.XMLStreamException;
  import javax.xml.stream.XMLStreamWriter;

  public class WriteXml {

    public static void main(String[] args) {
      XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
      String filename = "data.xml";

      try {
        XMLStreamWriter xmlStreamWriter =
          xmlOutputFactory.createXMLStreamWriter(
          new FileOutputStream(filename), "UTF-8");

          xmlStreamWriter.writeStartDocument("UTF-8", "1.0");
          xmlStreamWriter.writeCharacters("\n");
          xmlStreamWriter.writeStartElement("data");
          xmlStreamWriter.writeCharacters("\n");

          xmlStreamWriter.writeStartElement("firstName");
          xmlStreamWriter.writeCharacters("John");
          xmlStreamWriter.writeEndElement();
          xmlStreamWriter.writeCharacters("\n");

          xmlStreamWriter.writeStartElement("lastName");
          xmlStreamWriter.writeCharacters("Smith");
          xmlStreamWriter.writeEndElement();
          xmlStreamWriter.writeCharacters("\n");

          xmlStreamWriter.writeStartElement("phone");
          xmlStreamWriter.writeCharacters("916-555-4418");
          xmlStreamWriter.writeEndElement();
          xmlStreamWriter.writeCharacters("\n");

          xmlStreamWriter.writeEndDocument();

          xmlStreamWriter.flush();
          xmlStreamWriter.close();
      } catch(XMLStreamException | FileNotFoundException e){
        e.printStackTrace();
      }
    }
  }

XML is slowly being replaced by JSON, but that's a story for another time.


Kyle Eggleston
kyle@dreamsense.com
Copyright © 2003 - 2020