DOM to XML

I am trying to create an XML file using DOM and a HashMap to enter data.
1- How can I link my HashMap to teh DOM code
2- Why FileWriter is printing only one line in the file
3- Am I missing something?
Thank you
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import org.w3c.dom.*;
public class MyHashmap
     public static void main(String[]args)
          try
               DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
               DocumentBuilder builder = factory.newDocumentBuilder();
               Document doc = builder.newDocument();
                    Element e= doc.createElement("names");
                    Text ee = doc.createTextNode("address");
               doc.appendChild(e);
               e.appendChild(e);
               TransformerFactory tf = TransformerFactory.newInstance();
               Transformer transformer = tf.newTransformer();
               DOMSource source= new DOMSource(doc);
               StringWriter strwriter = new StringWriter();
               StreamResult strresult = new StreamResult(strwriter);
               transformer.transform(source,strresult);
               String result = strwriter.toString();
               FileWriter fw = new FileWriter("result.txt");
               fw.write(result);
               fw.close();
          catch (ParserConfigurationException e1)
               e1.printStackTrace();
          catch (TransformerConfigurationException e)
               e.printStackTrace();
          catch (TransformerException e)
               e.printStackTrace();
          } catch (IOException e) {
               e.printStackTrace();
     public void hashMap(String names, String address)
          HashMap hmap = new HashMap();
          MyHashmap mymap = new MyHashmap();
          hmap.put("names", "address");
          System.out.println(hmap.entrySet());
}

to write nicely formatted XML use this:
            FileOutputStream fos = new FileOutputStream(file);
            TransformerFactory tf = TransformerFactory.newInstance();
            try {
                Transformer t = tf.newTransformer();
                t.setOutputProperty("encoding", "iso-8859-1");
                t.setOutputProperty("indent", "yes");
                t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
                DOMSource domsource = new DOMSource(document);
                StreamResult sr = new StreamResult(fos);
                t.transform(domsource, sr);
            } catch (TransformerConfigurationException tce) {
                tce.printStackTrace(System.err);
            } catch (TransformerException te) {
                te.printStackTrace(System.err);

Similar Messages

  • [Q] convert DOM to XML Document

    Hi,
    Is there any class or library which convert DOM to XML document?
    ----- java program ------------
    import org.w3c.dom.*;
    import org.apache.crimson.tree.XmlDocument;
    public class Sample {
      public static void main(String args[]) {
        // create a document and root element
        Document doc = new XmlDocument();
        Element root = doc.createElement("html");
        doc.appendChild(root);
        // append a data
        Element body = doc.createElement("body");
        root.appendChild(body);
        body.appendChild(doc.createTextNode("Hello"));
        // convert DOM to XML Document
    }----- expected result ----------
    <html>
    <body>
      Hello
    </body>
    </html>Could you help me?

    Hi,
    Look at the package javax.xml.transform
    or
    try the following code:
    I tried the following code.
    ----- java program ------------
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    import java.io.OutputStream;
    public class Sample {
      public static void main(String[] args) {
        try {
          // create a document and root element
          Document doc = DocumentBuilderFactory.newInstance()
                                .newDocumentBuilder()
                                .newDocument();
          Element root = doc.createElement("html");
          doc.appendChild(root);
          // append a data
          Element body = doc.createElement("body");
          root.appendChild(body);
          body.appendChild(doc.createTextNode("Hello"));
          Element ul = doc.createElement("ul");
          String[] list = {"foo", "bar", "baz"};
          for (int i=0; i<list.length; i++) {
           Element li = doc.createElement("li");
           li.appendChild(doc.createTextNode(list));
         ul.appendChild(li);
    body.appendChild(ul);
    // convert DOM to XML Document
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    //OutputStream stream = new FileOutputStream("output.xml");
    OutputStream stream = System.out;
    transformer.transform(new DOMSource(doc), new StreamResult(stream));
    } catch (Exception ex) {
         ex.printStackTrace();
    ----- result ------------
    <html>
    <body>Hello<ul>
    <li>foo</li>
    <li>bar</li>
    <li>baz</li>
    </ul>
    </body>
    </html>Great! Very thanks!

  • Can anyone help me in converting a dom to xml

    hi,
    i am facing a problem in using transformer factory to convert a dom to xml.
    please help me.
    if anyone has a sample code in java please share with me.

        static public void serialize( Document doc, File outFile)
            try
               TransformerFactory tfFac = TransformerFactory.newInstance();
               Transformer tf = tfFac.newTransformer();
               // tf.setOutputProperty("indent", "yes");
               tf.transform(new DOMSource(doc),
                  new StreamResult(new FileWriter( outFile )
            }         // end of try
            catch( FileNotFoundException fnfe )
               System.err.println( "File Creation Error in serializer" );
               System.err.println( fnfe.getMessage() );
            }         // end of catch
            catch (TransformerException e)
                e.printStackTrace();
            }         // end of catch
            catch( IOException ioe )
               System.err.println( "IOException in serializer" );
               System.err.println( ioe.getMessage() );
            }         // end of catch
        }Dave Patterson

  • HTML held in DOM (as XML) rendered onto JEditorPane

    I am interested to know if anyone out there has any ideas on the following?:
    I am holding an html document as a DOM object as it is part of an xml message (which undergoes various transformations) that is passed through our software.
    The problem is that to do this I have had to make the html into a 'well-formed' xml document (which doesn't conform to html 3.2)
    Basically this causes problems where I want to use html elements that forbid end tags (e.g. <br> or <img>), in that the DOM when written out contains these end tags (so <br> becomes <br></br> or
    This actually works fine in IE (as it's quite lenient to these things) but when you put it in a JEditorPane it displays a spare > (not quite sure on it's logic!).
    So... does anyone have any good ideas?? My only thought was to extend the HTMLEditorToolKit to be more lenient with these but that strikes me as being a bit hard! I know I can get around it by putting spaces in for things like img (e.g. <img src="bla.gif"> </img> displays fine whereas <img src="bla.gif"></img> displays the image and then a > symbol!)

    If anyone is still interested in this tread, an article was written on this subject and ways to work around it:
    http://www.xml.com/pub/a/2000/08/30/xsltandhtml

  • Java DOM Parser (XML)

    Could someone please give me a link where I can find a example of a DOM parser, w3c. That shows how to parse an xml string or file and build the tree then access parts of it? I cant find a basic example anywhere!

    Check this
    http://java.sun.com/xml/jaxp/dist/1.1/docs/tutorial/dom/1_read.html

  • Java servlet, DOM and xml help! please urgent!

    I have to write a servlet that takes the user input to build a xml document using DOM API and should be able to append new entry to that xml file whenever any user adds an entry. I have written the fillowing code, can anyone please take a look at this code and tell me the right way to do it as this code is actually not creating any xml file and also in commented line of this code I tried by giving blank xml file name with just root element, so that this code can enter new elements like name, title as child element of the root, but doesn't work.
    PrintWriter out = res.getWriter ();
    res.setContentType ("text/html");
    try
    Document xmldoc = null;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    DOMImplementation impl = builder.getDOMImplementation();
    // Document xmldoc = builder.parse(xmlfile name);
    Element e = null;
    Node n = null;
    String name = req.getParameter("name");
    String title = req.getParameter("title");
    String address = req.getParameter("address");
    xmldoc = impl.createDocument(null, "records", null);
    Element root = xmldoc.getDocumentElement();
    e = xmldoc.createElementNS(null, "name");
    n = xmldoc.createTextNode(name);
    e.appendChild(n);
    root.appendChild(e);
    e = xmldoc.createElementNS(null, "title");
    n = xmldoc.createTextNode(title);
    e.appendChild(n);
    root.appendChild(e);
    e = xmldoc.createElementNS(null, "address");
    n = xmldoc.createTextNode(address);
    e.appendChild(n);
    root.appendChild(e);
    DOMSource domSource = new DOMSource(xmldoc);
    Source xslSource = new StreamSource (xsl file);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer(xslSource);
    transformer.transform(domSource,new StreamResult (out));

    Document xmldoc = null;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    xmldoc = documentBuilder.newDocument();
    Element e = null;
    Node n = null;
    String name = req.getParameter("name");
    String title = req.getParameter("title");
    String address = req.getParameter("address");
    e = xmldoc.createElement("name");
    n = xmldoc.createTextNode(name);
    e.appendChild(n);
    xmldoc.appendChild(e);
    e = xmldoc.createElement("title");
    n = xmldoc.createTextNode(title);
    e.appendChild(n);
    xmldoc.appendChild(e);
    e = xmldoc.createElement("address");
    n = xmldoc.createTextNode(address);
    e.appendChild(n);
    xmldoc.appendChild(e);
    DOMSource domSource = new DOMSource(xmldoc);
    StreamSource xslSource = new StreamSource (xsl file);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer(xslSource);
    transformer.transform(domSource,new StreamResult (out));

  • Exception CX_SY_CONVERSION_CODEPAGE in DOM approach xML conversion

    Hi gurus,
    I got error like below while converting xml file to internal table by DOM parsing approch as said in the Robert Eijpe's blog.
    At the conversion of a text from codepage '4110' to codepage '4103':
    - a character was found that cannot be displayed in one of the two
    codepages;
    - or it was detected that this conversion is not supported
    The running ABAP program 'CL_ABAP_CONV_IN_CE============CP' had to b
      terminated as the conversion
    would have produced incorrect data.
    The number of characters that could not be displayed (and therefore
    be converted), is 2. If this number is 0, the second error case, as
    mentioned above, has occurred.
    Can anyone please help me to rid out of this error.
    Thanks,
    Thiyagu
    Edited by: Thiyagu on Dec 1, 2008 7:34 PM

    taht was not really helpful... can you tell us how you fixed this issue... I ahve the same problem

  • DOM to XML String

    Hi,
    I'm trying to transform a DOM object into a string of xml, but somehow it only outputs the first line.
    What did I do wrong?
              Document doc = processDoc();
              Source source = new DOMSource((Element) doc.getElementsByTagName("vancouver").item(0));
              StringWriter out = new StringWriter();
              StreamResult result = new StreamResult(out);
              Transformer xformer = TransformerFactory.newInstance().newTransformer();
              xformer.setOutputProperty("encoding", "iso-8859-1");
              xformer.setOutputProperty("indent", "yes");
              xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
              xformer.transform(source, result);
              return result.getWriter().toString();Thanks!
    Will

    Hi DrClap,
    this is how I constructed my DOM object:
         public Document processDoc() throws Exception {
              URL u = new URL("http://www.weatheroffice.ec.gc.ca:80/city/pages/bc-74_metric_e.html");
              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              DocumentBuilder builder = factory.newDocumentBuilder();
              // in doc
              Document inDoc = builder.parse(u.openStream());
              // out doc
              Document outDoc = builder.newDocument();
              // grab <div id="citytextf">
              Element inElement = inDoc.getElementById("citytextf");
              Element rootElement = inElement;
              // grab <h2>
              inElement = (Element) inElement.getElementsByTagName("h3").item(0);
              System.out.println(inElement.getTextContent());
              // create output root element
              Element outElement = outDoc.createElement("vancouver");
              outElement.setAttribute("issued", inElement.getTextContent().substring(11));
              rootElement = (Element) rootElement.getElementsByTagName("dl").item(0);
              // iterate thru city <dd>, <dt> tags
              NodeList tempList = rootElement.getElementsByTagName("dt");
              Element tempIn, tempOut;
              for (int i = 0; i < tempList.getLength(); i++) {
                   System.out.println(i);
                   tempIn = (Element) rootElement.getElementsByTagName("dt").item(i);     // grabs <dt> value
                   tempOut = outDoc.createElement("day");
                   tempOut.setAttribute("name", tempIn.getTextContent().trim());
                   tempIn = (Element) rootElement.getElementsByTagName("dd").item(i);
                   String input = tempIn.getTextContent();
                   (tempOut.appendChild(outDoc.createElement("high"))).setNodeValue(getHighLowValue("High", input));
                   (tempOut.appendChild(outDoc.createElement("low"))).setNodeValue(getHighLowValue("Low", input));
                   (tempOut.appendChild(outDoc.createElement("note"))).setNodeValue(getNoteValue(input));
                   System.out.println(((Element) tempOut).getAttribute("name"));
                   outElement.appendChild(tempOut);
              return outDoc;
         }which is suppose to output XML like this:
    <vancouver issued="Issued 6.30 PM PDT Saturday 16 April 2005">
      <day name="Tonight">
        <high></high>
        <low>6</low>
        <note>Cloudy. 60 percent chance of showers. Risk of small hail this evening.</note>
      </day>
      <day name="Sunday">
        <high>12</high>
        <low></low>
        <note>A few showers.</note>
      </day>
      <day name="Monday">
        <high>13</high>
        <low>6</low>
        <note>A mix of sun and cloud.</note>
      </day>
      <day name="Tuesday">
        <high>13</high>
        <low>6</low>
        <note>Sunny</note>
      </day>
      <day name="Wednesday">
        <high>15</high>
        <low>7</low>
        <note>Sunny</note>
      </day>
    </vancouver>
          But all it outputs is:
    <?xml version="1.0" encoding="iso-8859-1"?>I just started learning XML in Java so there're probably things that I missed out on.
    Thanks!

  • Saving DOM to *.xml using JAXP only !

    There are tons of question regarding this topic in the forum already.
    But i'm willing to run thru the DOM to write back into the file , the problem is how do i acces the first to lines like dtd declaration etc ..
    any cues?

    try this :
    <code>
    TransformerFactory xformFactory = TransformerFactory.newIntance();
    Transformer idTransfrom = xformFactory .newTransformer();
    FileOutputStream file = new FileOutputStream("file.xml");
    idTransfrom.transform(new DOMSource(document),new StreamResult(file));
    file.close();
    </code>

  • XML - DOM tree - XML

    I'm building an application that takes an xml file, turns it into a DOM tree, then the user selects different options from a database to manipulate the internal information gathered by the original XML file, the program is a process and at the end of the process the original XML file has been updated with new information, i need help with finding some code to take the DOM tree information displayed to the user and save back out as a new XML file. any help would be greatly appreciated.

    You can use JDOM, Xerces XMLSerializer, or J2SE's Transformer. The first 2 are pretty simple. The 3rd isn't too hard. An example can be found in code sample 3 on http://java.sun.com/developer/technicalArticles/xml/JavaTechandXML_part3/.

  • Transform DOM as XML ????????

    Hi Friends
    I have created a DOM for an XML file and then I edited that DOM.
    Now Please if it is possible to TRANSFORM that DOM again as an XML file instead of HTML file.
    One mode thing if i have a dom and I want to add CDATA to specific NODE how do we do it .. Please let me know.
    Any help would be great.
    Thanks

    How to add a CDATA section to a NODE, provided that the DTD allows a CDATA section to be added to a NODE you can do the following:
    This is the general idea: you will have to check if it compiles.
    //Create a CharacterData node from a Document. The document represents a DOM which was either created from an xml file or is being created on the file.
    CharacterData cdata = document.createCDATASection("The character data");
    //Find the node that you want by using a search algorithm:
    public boolean findNode(Node root, String elementName,
    CharacterData cdata){
    if(root instanceof Text){
    System.out.println("element is a text node");
    return false;
    //if you have found the node with local name ==
    //elementName. Then append the cdatasection as a
    //child
    if(root.getLocalName().equals(elementName)){
    System.out.println("Found Node");
    root.appendChild(cdata);
    return true;
    if(!root.hasChildNodes()){
    System.out.println("element has no children");
    return false;
    //Run through the children for root and for each //recursively see if any of their children is the desired node.
    NodeList childNodes = root.getChildNodes();
    int noChildren = childNodes.getLength();
    boolean result = false;
    for(int i = 0; i<noChildren; i++){
    if(!result){
    System.out.println("About to find next child");
    result = findNode(childNodes.item(i),
    elementName, cdata);
    }else break;
    return result;
    Hope this helps.

  • Losing "xmlns" when transforming DOM to XML file in OC4J

    I am outputting a DOM to a file using the standard transformation approach. When executed within JDeveloper everything works fine. However, when wrapped in a webservice using JDeveloper and run within OC4J the output is missing the "xmlns" attribute from the root node. Anyone have an idea why this is happening and what a workaround would be?
    The original XML root element is:
    &lt;e2579ReportAssemblyList xmlns="http://cdrh.fda.gov/schema/e2579ReportAssembly.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xs:noNamespaceSchemaLocation="http://cdrh.fda.gov/schema/e2579ReportAssembly.xsd e2579ReportAssembly.xsd"&gt;
    You can see the xmlns attribute has been provide. I have verified that the attributes are correct while in the DOM.
    The xml root element after saving to DOM using transformation is:
    &lt;e2579ReportAssemblyList xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xs:noNamespaceSchemaLocation="http://cdrh.fda.gov/schema/e2579ReportAssembly.xsd e2579ReportAssembly.xsd"&gt;
    You can see the xmlns attribute is now blank.
    The approach used in the transformation is as follows:
    File mOutput = new File(mFileNamePath);
    FileOutputStream mOutputStream = new FileOutputStream(mOutput);
    Transformer mTransformer = TransformerFactory.newInstance().newTransformer();
    mTransformer.transform(new DOMSource(mNextBatchItem), new StreamResult(mOutputStream));
    mOutputStream.close();
    Any suggestions would be greatly appreciated.

    If no one knows why this is happening in the transform, is there another reliable way of outputting the DOM to an XML file?

  • DOM parsing XML

    Hello guys,
    I have a huge xml document with lots of nested tags I would want to be able to specify a tag and get the values that comes underneath that tag. Iam able to do that if i dont have any tags nested under the tag that am specifying.
    How do i go about if i have tags nested within the parent tag?
    I would really appreciate your help guys
    Kay

    Use XPath.
    http://www.onjava.com/pub/a/onjava/2005/01/12/xpath.ht
    mlThanks for the lead. I did use XPath and it was great. But one question.
    XPath xpath = XPathFactory.newInstance().newXPath();
    String str = xpath.evaluate(expression, doc);
    The string that i get is values in the xml document but is in the exact format of the xml. i mean each value is printed in one line.
    Is there better ways to get the results?
    Thanks again
    kay

  • [iPhone sdk] DOM/create XML support?

    Is there any way to create arbitrary XML on the iPhone other than the low-tech solution of using strings?
    Most environments I've worked in have support for building up a document, i.e.
    document doc = new document(root);
    addElement("myelem1").setText("sometext1");
    addElement("myelem2").setText("sometext2");
    mystring = doc.asXml();
    You get the idea. The underlying API handles all the tag generation, entity replacement, etc. Is this available in the iPhone SDK somewhere?
    Thanks in advance.

    Google has written an almost drop in replacement of NSXMLDocument. I say almost because initWithContentsOfURL is not implemented, nor is -nodesForXPath:error. There may be others that are missing, but it worked for me once I initialized it with an NSString instead of a URL. This replacement is part of the Google Data API. There are only 3 classes that need to be imported out of the whole library. You will also need to add libxml2 to the Frameworks and update your build headers.
    See http://notes.bikemonkey.org/post/47351363/googles-nsxmldocument-replacement-for- iphone
    The XML replacement is only in SVN for the moment, see http://code.google.com/p/gdata-objectivec-client/source/checkout to get it.

  • Creating a dynamic jtree using datas retrieved by dom in xml parsing

    help me with code to create a dynamic jtree using data retrieved as nodes by xml parsing using dom

    Ok, so you want to make a tree. To determine the data that appears in a tree, you have to make a custom tree model. The API for this is at :
    http://java.sun.com/j2se/1.4.2/docs/api/
    A tutorial for using trees is at :
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
    I assume you are going to be using Nodes, since you are using XML. For this I might start with something like
    class NodeTreeModel implements TreeModelI would then implement the 'getChildCount()' as the number of subnodes a node has, and the value of a tree node to the nodes value.
    Hope that starts you off.

Maybe you are looking for

  • Values not getting printed in the Output

    Hi all,     Iam facing strange problem. In the debug mode iam seeing the values for all variables ( Variable windows) but after printing no value is getting printed. MAIN window is there but no element is being called from the MAIN window. Can anyone

  • Optical mouse problems

    I can't find answers or a closely related discussion. My Logitech Optical mouse started doing strange things today and was really bad, is now a bit better..but still not right. I can't open the 3 different volume icons on my desktop, except by highli

  • Duplicate account. Was told 10x this was solved no...

    I have the misfortune of being a BT customer since February. It took them 2 months to get me connected and then I started to receive 2 bills each month with 2 different phone number and account numbers. After countless telephone calls with incompeten

  • Impact of changing IP addresses

    Hi Experts, our company plans to assign new IP addresses to our Orchestrator servers. Are there any changes required to ensure this goes smoothly, or will there be no impact following the re-IP? Servers in scope include SCO Management server, SCO

  • Why does my keychain keep asking for my password every time I access the same web site?

    The ClamXav scan found 4 virus/trojan problems and quarantined them. Before I did thid, my keychain keeps popping up asking me if I want to save my password everytime I visit the same web site(s). Is there an issue with this? And how to I fix it?