Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;

public class Main {
    public static String getXMLData() {
        return "<a><person><name>myName</name></person></a>";
    }

    public static void main(String[] argv) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(getXMLData())));

        makeNamelist(doc);

        System.out.println(documentToString(doc));

    }

    private static void makeNamelist(Document doc) {
        String names = null;
        Element root = doc.getDocumentElement();
        NodeList nameElements = root.getElementsByTagName("name");
        for (int i = 0; i < nameElements.getLength(); i++) {
            Element name = (Element) nameElements.item(i);
            Text nametext = (Text) name.getFirstChild();
            if (names == null) {
                names = nametext.getData();
            } else {
                names += ", " + nametext.getData();
            }
        }
        Element namelist = doc.createElement("names");
        Text namelisttext = doc.createTextNode(names);
        namelist.appendChild(namelisttext);
        root.insertBefore(namelist, root.getFirstChild());
    }

    public static String documentToString(Document document) {
        try {
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer trans = tf.newTransformer();
            StringWriter sw = new StringWriter();
            trans.transform(new DOMSource(document), new StreamResult(sw));
            return sw.toString();
        } catch (TransformerException tEx) {
            tEx.printStackTrace();
        }
        return null;
    }
}