?
Solved

XML outputter/ DOM parser

Posted on 2005-03-07
18
Medium Priority
?
477 Views
Last Modified: 2013-11-23
Hi,

  I need to create some class to out put the following xml format string:

<adf>
      <prospect>
            <id sequence="1" source="Provider">800</id>
            <requestdate>2004-03-10T23:50:53-05:00</requestdate>
            <vehicle interest="buy" status="new">
                  <year>2004</year>
                  <make>MERCEDES-BENZ</make>
                  <model>E-Class</model>
                  <trim>E320 Rwd 4dr Sedan (3.2L 6cyl 5A)</trim>
            </vehicle>
            <customer>
                  <contact>
                        <name part="first">John</name>
                        <name part="last">Doe</name>
                        <email>valid@email.com</email>
                        <phone time="nopreference" type="voice">908-676-2365</phone>
                        <address>
                              <street line="1">7820 Baymeadows Rd. E</street>
                              <city>Beverly Hills</city>
                              <regioncode>CA</regioncode>
                              <postalcode>90210</postalcode>
                              <country>USA</country>
                        </address>
                  </contact>
                  <timeframe>
                        <description>Month</description>
                  </timeframe>
                  <comments>ADDITIONAL INFO: Additional comments</comments>
            </customer>
            <vendor>
                  <id source="AutoNation">122035</id>
                  <vendorname>DealerDirect</vendorname>
            </vendor>
            <provider>
                  <id source="Program Code">Provider Id</id>
                  <name part="full">Provider Name</name>
                  <service>Program Code</service>
            </provider>
      </prospect>
</adf>

Is there someone can provide some code? I need a api to return the above string(do not need to print it out).

0
Comment
Question by:richardluo
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 7
18 Comments
 
LVL 5

Expert Comment

by:Naeemg
ID: 13483623
// import these apis

import org.w3c.dom.*;
import org.w3c.dom.Document;


// create DOM document with the root name as ur is <adf>

    Document doc = null;
    try
    {
      DOMImplementation domImpl = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .getDOMImplementation();

      //System.out.println(rootNode);
      doc = domImpl.createDocument(null, "adf", null);

    }
    catch(ParserConfigurationException e)
    {
      System.err.println(e.getMessage());
      //e.printStackTrace(System.err);
    }
    catch(DOMException e)
    {
      System.err.println(e.getMessage());
      //e.printStackTrace(System.err);
    }

//now ur DOM object is created with the root node <adf>

//now u've to create sub elements with their respective attributes,so

//suppose ur next child element is <prospect>

Element prospect = doc.createElement("prospect");

// now create next element node, suppose <id>
Element id = doc.createElement("id");
// to create its attribute nodes.
id .setAttribute("sequence", "1");
id .setAttribute("source", "Provider");
// now creat text node for el <id>
id .appendChild(doc.createTextNode("800"));

//now append this element to its parent element <prospect>
prospect.appendChild(id);

//now append this element to root node as.
doc.getDocumentElement().appendChild(prospect );

//-- and add all element in viceversa.
now at the end when u want to get the output string
simply type the following command

doc.getDocumentElement().toString();

// hope will help u.

0
 

Expert Comment

by:quarkCN
ID: 13484383
use DOM4J.jar  it's very easy
0
 

Author Comment

by:richardluo
ID: 13489080
Hi guys,

  Thanks for the help. When I tried the code which provided by Naeemg, I got only this result:
[adf: null]

Did I missed something ?

Thanks

Richard
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 5

Expert Comment

by:Naeemg
ID: 13493531
dear richardluo
I tested my above code, it works fine, and displays the followoing output.

<adf><prospect><id sequence="1" source="Provider">800</id></prospect></adf>

did u test it by displaying last line? or by writting to disk?
 
try last line as

    System.out.println(doc.getDocumentElement().toString());

if it displays desired output. then you might have problem in writting it to ur file.
0
 
LVL 5

Expert Comment

by:Naeemg
ID: 13494310
aren't u using JDK 1.5 or JVM 5.0?
0
 

Author Comment

by:richardluo
ID: 13498389
Dear Naeemg,

  Thanks for your response. I am using jdk 1.4.1 and the following is my code:


      public static void testPost2()
      {
                  Document doc = null;
                  try
                  {
                    DOMImplementation domImpl = DocumentBuilderFactory.newInstance()
                        .newDocumentBuilder()
                        .getDOMImplementation();
            
                    doc = domImpl.createDocument(null, "adf", null);
            
                  }
                  catch(ParserConfigurationException e)
                  {
                    System.err.println(e.getMessage());
                  }
                  catch(DOMException e)
                  {
                    System.err.println(e.getMessage());
                  }

            
                  Element prospect = doc.createElement("prospect");
                  
                  Element id = doc.createElement("id");
                  id .setAttribute("sequence", "1");
                  id .setAttribute("source", "Provider");
                  id .appendChild(doc.createTextNode("800"));
                  
                  prospect.appendChild(id);
                  
                  doc.getDocumentElement().appendChild(prospect );
                  
                  System.out.println(doc.getDocumentElement().toString());

      }
      
      public static void main(String argv[])
      {
            testPost2();

      } //end of main


The printed out result is:    [adf:null]

Please let me know if I did something wrong

Thanks

Richard
0
 
LVL 5

Expert Comment

by:Naeemg
ID: 13499656
I'm surprised yar,
I've tested on JDK 1.4.2
and it works fine.

i will tell u its alternate in morning, but that will take much time to process.

regards
0
 

Author Comment

by:richardluo
ID: 13511877
Hi Naeemg,

  Are you sure that statment       doc.getDocumentElement().toString()    converts the structure of tree into :

<adf><prospect><id>..... </adf>  format ?
0
 
LVL 5

Expert Comment

by:Naeemg
ID: 13515361
hi richardluo, my code works fine on JDK 1.4. but i also got the problem u r facing on JDK 1.5. and I overcame it.
so you should try also the following extensions. definitly help u.

append following code , or make new method,

  try
  {
    javax.xml.transform.TransformerFactory tFactory = javax.xml.transform.TransformerFactory.newInstance();
    javax.xml.transform.Transformer transformer = tFactory.newTransformer();

    javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(doc);
    javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(new File(System.out));
    transformer.transform(source, result);
  }
  catch (TransformerConfigurationException ex)
  {
  }
  catch (TransformerException ex)
  {
  }
  catch (TransformerFactoryConfigurationError ex)
  {
  }



// also make the following changes according to ur requirment.
if u want to print structure on the screen then leave it as, otherwise replace
System.out with ur full file path. using file path, it will save ur structure in given file.

javax.xml.transform.stream.StreamResult(new File(System.out));
    transformer.transform(source, result);
 
0
 

Author Comment

by:richardluo
ID: 13519595
Hi Naeemg,

  I modified my code, but still got null. Please see the following code and let me know if I did something wrong.



      public static void testPost2()
      {
                  Document doc = null;
                  try
                  {
                    DOMImplementation domImpl = DocumentBuilderFactory.newInstance()
                        .newDocumentBuilder()
                        .getDOMImplementation();
            
                    doc = domImpl.createDocument(null, "adf", null);
            
                  }
                  catch(Exception e)
                  {
                    System.err.println(e.getMessage());
                  }

            
                  Element prospect = doc.createElement("prospect");
                  
                  Element id = doc.createElement("id");
                  id .setAttribute("sequence", "1");
                  id .setAttribute("source", "Provider");
                  id .appendChild(doc.createTextNode("800"));
                  
                  prospect.appendChild(id);
                  
                  doc.getDocumentElement().appendChild(prospect );
                  
            
                  
            try
             {
               javax.xml.transform.TransformerFactory tFactory = javax.xml.transform.TransformerFactory.newInstance();
               javax.xml.transform.Transformer transformer = tFactory.newTransformer();

               javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(doc);
               //This line gives compiling error:  
               //javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(new File(System.out));
               //transformer.transform(source, result);
             }
             catch (TransformerConfigurationException ex)
             {
             }
             catch (TransformerException ex)
             {
             }
             catch (TransformerFactoryConfigurationError ex)
             {
             }
             
              String result = doc.getDocumentElement().toString();
             
                                 // Basically, I just need a string, print it out just for testing purpose
              System.out.println(result);
            
      }

Thanks
0
 
LVL 5

Accepted Solution

by:
Naeemg earned 800 total points
ID: 13525109
i'm sorry dear richardluo, it was my mistake.
actually that line is making problem while compiling due to new File() commain in it.
that is actually used when writting to file.

make followoing changes at that area.

if u want to jsut print the result out. then use the following

javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(System.out);

and if u want to write result to any file , then use the following .

javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(new File("C:\\temp.xml"));

test it and tell me.

0
 

Author Comment

by:richardluo
ID: 13550342
Hi Naeemg,

  Thanks for the response. It print it out correctly now. If I need put this result into a string, how I can do it?



BTW, I will travel tomorrow and coming back next week.

Thanks
0
 

Author Comment

by:richardluo
ID: 13607977
Hi Naeemg,

  I am coming back, do you have an idea how to put result into a string ?

Thanks

Richard
0
 
LVL 5

Expert Comment

by:Naeemg
ID: 13608827
i didn't work on that, but u can write to file then read file and get data in string.
0
 

Author Comment

by:richardluo
ID: 13783818
I need a better solution here, I need put the result into a string, not write it to a file and read it back from the file. It doesn't sounds good. Naeemg, please help me to get there, Thanks.
0
 
LVL 5

Expert Comment

by:Naeemg
ID: 13788422
i think this is not bad idea, as developer have to create temp files many times during runtime according to requirments. assume this is u creating a temp file, and it will not take much time to write text to file and read it back.
i suggest u to first test this logic, and if u feel its not good, then close this question and post new one. that may be any other expert know that idea,, becoz this is v old question.
and also tell me the result of ur testing.

0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.
Suggested Courses
Course of the Month9 days, 17 hours left to enroll

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question