Writing a formatter in java to display XML file in an organized display

i have to write a formatter that reads in an XML file and outputs something..like a text file that displays the XML content. Normally when you open XML in text file, all u say is one line in which all the content is displayed..i want to wirte a program that will read in the XML and output a text file which shows the XML content in the same way like wen u view it on a browser..
thanks

ok here you go....this is rough and probably buggy.
Needs some real testing and refactoring and still does not work with
<! and
<?
tags, but for simple XML it should do about what you want.
import java.io.BufferedReader;
import java.io.FileReader;
public class XMLParse
    private static String OPEN_TAG = "OPEN_TAG";
    private static String CLOSE_TAG = "CLOSE_TAG";
    private static String SLASH = "SLASH";
    private static String LETTER = "LETTER";
    private static String SLASH_LETTER = "SLASH_LETTER";
    private static String GET_VALUE = "GET_VALUE";
    private static int INDENT_LEVEL = 4;
    public static void main(String[] args) throws Exception
        FileReader file = new FileReader( "props/test.xml" );
        BufferedReader fileInput = new BufferedReader( file );
        StringBuffer sb = new StringBuffer();
        String s;
        while ( (s = fileInput.readLine()) != null )
            sb.append( s );
        parseXmlString( sb.toString() );
    public static void printIndent(int x)
        for ( int i = 0; i < x * INDENT_LEVEL; i++ )
            System.out.print( " " );
    public static void print(String s)
        System.out.println( s );
    public static boolean isWhiteSpace(char c)
        boolean isWhite = false;
        if ( c == '\n' || c == '\t' || c == ' ' )
            isWhite = true;
        return isWhite;
    public static void parseXmlString(String s)
        char[] chars = s.toCharArray();
        int indentLevel = -1;
        String state = "";
        String latestTag = "";
        for ( int i = 0; i < chars.length; i++ )
            char c = chars;
if ( state.equalsIgnoreCase( GET_VALUE ) || !isWhiteSpace( c ) )
switch ( c )
case '<':
if ( state.equalsIgnoreCase( GET_VALUE ) )
printIndent( indentLevel + 1 );
print( "*" + latestTag );
state = OPEN_TAG;
latestTag = "";
break;
state = OPEN_TAG;
latestTag = "";
break;
case '>':
if ( state.equalsIgnoreCase( SLASH ) )
indentLevel--;
printIndent( indentLevel + 1 );
print( "+-" + latestTag );
state = CLOSE_TAG;
break;
if ( state.equalsIgnoreCase( SLASH_LETTER ) )
printIndent( indentLevel + 1 );
print( "-" + latestTag );
state = CLOSE_TAG;
break;
printIndent( indentLevel );
print( "+" + latestTag );
state = CLOSE_TAG;
break;
case '/':
if ( state.equalsIgnoreCase( OPEN_TAG ) )
indentLevel--;
state = SLASH;
break;
default:
if ( state.equalsIgnoreCase( OPEN_TAG ) )
indentLevel++;
latestTag += c;
state = LETTER;
break;
if ( state.equalsIgnoreCase( CLOSE_TAG ) )
latestTag = "";
latestTag += c;
state = GET_VALUE;
break;
if ( state.equalsIgnoreCase( LETTER ) )
latestTag += c;
state = LETTER;
break;
if ( state.equalsIgnoreCase( SLASH ) )
latestTag += c;
state = SLASH_LETTER;
break;
if ( state.equalsIgnoreCase( SLASH_LETTER ) )
latestTag += c;
state = SLASH_LETTER;
break;
if ( state.equalsIgnoreCase( GET_VALUE ) )
latestTag += c;
state = GET_VALUE;
break;

Similar Messages

  • Mapping java classes to XML files

    Hi Friends !!
    Please I need your help.
    Does somebody out there know any framework or API that helps me to map Java classes to XML files.
    Something like:
    public class Test {
        public int x;
        public int y;
        public int sum(){}
    }to something like:
    <?xml version="1.0" encoding="UTF-8"?>
    <class>
    <className>Test</className>
    bla
    bla
    bla
    </class>
    Any tips?
    Thanks in advance
    Cleverson

    JAXB will create classes from an XML schema, SAX is a parser library and JAXP is a library of XML a bunch of XML tools.
    I don't care for JAXB too much. I would skip it and go right to the JAX-RPC spec (WebServices).

  • Serializing Java Objects to XML files

    Hi,
    We looking for SAP library which can serialize Java Objects into XML files.
    Can you point us were to find it ?
    We have found such open source library called "XStream" at the following link
    http://www.xml.com/pub/a/2004/08/18/xstream.html
    Is it allowed to use that library inside SAP released software ?
    Thanks
    Orit

    How about https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/webcontent/uuid/83f6d2fb-0c01-0010-a2ba-a2ec94ba08f4 [original link is broken] [original link is broken]? Depends on your use cases...
    Both are supported in SAP NW CE 7.1.
    HTH!
    -- Vladimir

  • Java Tree's & XML Files ??

    Hi ye's -
    Listen I'm a little stuck - and need yer help ??? If ye's can .........please -
    The problem is this -
    I have a Massive XML File containing all the different Categories, Tags, Tag Descriptions, Indicators and valid Subfields, Repeatable Subfields.
    Now - I need to build a Tree to illustrate all this information - however within my code I don't want to Compare it against the elements int the XML file since I'll have tonnes of different elements, making my code enormous -
    Is there a way I can code in java to loop through the XML file and build up my Tree as it goes along ????
    Here is a sample of the code I was using - but surely theres an easier way ? Can't keep continuing like this ;o(
    Lorraine
    public void parseDomTreeMarc(Element rootElement)
    NodeList BiblioTags = rootElement.getChildNodes();
    DefaultMutableTreeNode Category = null;
    DefaultMutableTreeNode Tag = null;
    for(int i = 0; i < BiblioTags.getLength(); i++)
         if(BiblioTags.item(i).getNodeName().compareTo("Title") == 0)
              NodeList CategoriesList = BiblioTags.item(i).getChildNodes();
              Category = new DefaultMutableTreeNode(CategoriesList.item(i).getNodeValue());
              for(int j = 0; j < CategoriesList.getLength(); j++)
                   if(CategoriesList.item(j).getNodeName().compareTo("TagValue") == 0)
                        NodeList TagList = CategoriesList.item(j).getChildNodes();
                        for(int k = 0; k < TagList.getLength(); k++)
                             switch(TagList.item(k).getNodeType())
                                  case Node.TEXT_NODE:
                                  if(TagList.item(k).getNodeValue().compareTo("") != 0)
                                       Tag = new DefaultMutableTreeNode(TagList.item(k).getNodeValue());
                                       Category.add(Tag);
                             if(TagList.item(k).getNodeName().compareTo("TitleDescription") == 0)
                                       etc...
                                       doing same piece of code for all elements more or less ...
         //Create Marc Tree
    final JTree marcTree = new JTree(Category);
    marcTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    JScrollPane treeView1 = new JScrollPane(marcTree);
    this.getContentPane().add(treeView1, new XYConstraints(10, 350, 223, 197));

    Have emailed a jar file of sample code to the email address shown in your profie. Let me know if there's a better address to send it to
    Good luck!

  • How to generate reportdesign dynamically using java with out xml file

    hi
    how can i generate a reportdesign dynamically using java with out passing xml file to jasperDesign , i want to create my reportdesign with out xml file
    how can i ,please help
    thanks

    LiveCycle does provide a Java API to forms; LiveCycle is in fact a suite of programs, mostly enterprise level for running on server (next to which the cost of the master suite is a drop in the ocean). LiveCycle Designer is perhaps the only end user tool, and it is not for server use and doesn't have an API.
    Are you looking for a server solution? If so, nothing in the master suite can help, it isn't for server use.

  • How to generate Java objects from XML files with out  scema compilation

    Dear participants,
    My name is Raghavendra , i have a requirement of reading XML files Dynamically and parse them and create java types for manipulation . i will not be provided with sxd files (no schema compilation )coz no one knows how many types of structures are there. i want a generic solution. Please Help.
    Thanks ,
    Raghavendra Ach
    you can mail me to " [email protected]"

    georgemc wrote:
    You could also look at something like Apache Digester, which will parse your XML and populate Java objects with the data. A slightly steeper learning curve than the lower-level APIs such as JDOM, but that's outweighed by the lesser development effortdon't think that would work for the original problem, which seemed to indicate that the xml had an unknown structure.

  • Quiz using Java Script and XML file

    Hi,
    I am student from Liverpool in the UK. I am currently making a "quiz" website that links to an xml document, and brings back results of how the user has done.
    I have made the website, and linked it to the xml document, but I can't get javascript to tell the user how many answers they got correct. Can you help me?
    A friend told me to use a function, and then link that function to a box that, when clicked, brings up an alert box telling the user how many they got correct.
    I know this is probably very simple, but I would be very grateful for help in which exact commands to write that will bring up an alert box when the user clicks on a "Submit" button. This alert box should bring up how many correct answers (out of 10) the user obtained.
    Thanks for your time,
    Matthew Tickle.

    Java and Javascript are completely different. You probobally wont get much here... maybe u should try to find a javascript forum or look at some tutorials: http://tutorials.findtutorials.com/index/category/20

  • Customize -java-wsdl-mapping.xml with EJB3 web service

    Using OC4J 10.1.3, I have an EJB that I am exposing as a web service using JSR-181 annotations. Is it possible to customize the generated <ServiceName>-java-wsdl-mapping.xml file? I tried putting my own version in META-INF/ of my ejb jar, but it didn't seem to pick up on it.

    I was told the product manager and/or developers from Oracle watched this board. Doesn't anyone have a response to this?

  • Ignore some fields while saving a Java class into XML

    Hi!
    I've seen in this forum that there is an easy way of saving Java classes to XML files using Castor. I want to save some Java classes into XML, but not all the fields of the class. For example, I want to ignore all lists. Is there any easy way to do something like this:
    class Java2XML{
              public static void makeXML(Object object)
                        for all fields in object
                                  if field extends List, ignore
                                  else, include field in XML
    }Thanks in advance!

    You can add a managed bean by:
    - manually adding a definition in the faces config source tab.
    - creating a bean in the overview tab of the faces-config editor.
    So yes, you can edit the faces-config manually.
    I hope this answer your question,
    Regards,
    Koen Verhulst

  • How to display XML file in java swing

    hi all
    now i do my M.Sc., project on data maining.this time i have one problem,thats i can't display XML file in swing frame.so any one know this plz give me that idea or code.
    Thanks to all.
    RSK

    One way of doing that is to use JDOM...
    u create an xml tree, and then output using XMLOutputter class...it will be displayed in text...im not sure if thats what u want...however, if u do want to represent it visually then u may need to draw a tree...u may use the Graphics2D for that...there are alot of ways to do such thing, and the 2 possibilities arent the best...depends on what u want...elaborate more pls.

  • Writing XML Files in Java

    Hi,
    How do I WRITE to XML Files.I know parsing is for reading but what is for writing?
    Thankx in advance...

    JAXP1.1 can be used for parsing the XML file to read/write from/to XML file.A node can be created or any node Value can be updated or changed using XML parser.Using TransformerFactory and Transformer class one can write back to any XML file.
    If U still want any help write back to me.
    Thanx

  • Create dynamically xml file from java.

    Hi all,
    I got class information in java program. I have to put method name and return type into xml. The xml file is like this and i have created this file.
    <method>
    <name></name>
    <returnType></returnType>
    </method>
    Now when I get method information I want to put it in xml, not by writing each method name explicitly in file, mean i have to load this xml into memory for that what should i do?
    Please help me I am new in XML.
    Thanks in advance.
    -regards
    bunty

    If you save your XML file as "methodinfo.xml", you can use the following code:import java.io.File;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder parser = factory.newDocumentBuilder();
      Document doc = parser.parse(new File("methodinfo.xml"));
      Node nameNode = doc.getElementsByTagName("name").item(0);
      Node returnTypeNode = doc.getElementsByTagName("returnType").item(0);
      nameNode.setTextContent("the name of the method");
      returnTypeNode.setTextContent("the return type of the method");
      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(System.out);
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      System.out.println("This is the content of the XML document:\n");
      transformer.transform(source, result);
    catch (Exception e){
    ...The content of the XML document will be displayed as follows:<?xml version="1.0" encoding="UTF-8" ?>
    <method>
      <name>the name of the method</name>
      <returnType>the return type of the method</returnType>
    </method>

  • XML file is not being displayed in browser? Why?

    Hi all!
    I have a secnario file->XI->J2EE appl.
    I am using  File sender adapter and HTTP Receiver adapter.
    I placed XML file in D:\somedir of my machine, it is picking up well by XI, <b>all i want to know is how XI sends this XML file to my J2EE Appl.</b>Because my servlet should display the same XML file in browser. I deployed my J2EE appl on weblogic application server9.0 I am getting the following error:
    The XML page cannot be displayed
    Cannot view XML input using style sheet. Please correct the error and then click the Refresh button, or try again later.
    XML document must have a top level element. Error processing resource 'http://localhost:7001/Invoke/DisplayRes'.
    These are settings that i have given in my Receiver HTTP adapter:
    Aadapter Type: HTTP
                       Receiver
    Transport Protocol:  HTTP1.0
    Message Protocol:    XI payload in HTTP body
    Adapter Engine:      Integration Server
    Addressing Type:     URL address
    Target host:         localhost
    Service Number:      7001(Port number of Weblogic appl server--where my J2EE appl is deployed).
    Path     :  /Invoke/DisplayRes/(Context path of J2EE appl)
    Authentication Type:Use Logon Data for SAP System
    Content Type: text/xml
    Username:   xiappluser
    password:   xx
    XML code:   UTF-8
    This is my Servlet code:
    public class DisplayRes extends HttpServlet {
         public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
         doPost(request,response);
         public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
         BufferedReader brin =new BufferedReader(new InputStreamReader(request.getInputStream()));
         String inputLine;
         StringBuffer sBuf = new StringBuffer();
         PrintWriter out = response.getWriter();
         response.setContentType("text/xml");
         while ((inputLine = brin.readLine()) != null)
             sBuf.append(inputLine);
               out.println(sBuf.toString());
              brin.close();
             out.flush();
    Where i went wrong please help me,
    NOTE: I want to know how XI sends XML file to my J2EE appl. I suppose my servlet receives it in request object.If so can i use like:
    response.setContentType("text/xml");
      String xmlFile = request.getParameter("myXMLFile");
      PrintWriter out = response.getWriter();
      out.write(xmlFile);
      out.flush();
      out.close();
    Please help me!
    Thanks a lot!

    Hi Datta,
    You seem to have big problem with this scneario as you have raised this question couple of times , in couple of topics / threads. I will try to make a few things about this clear.
    1. XI when sends data to a J2EE application , in your case a servlet, I believe you must be using a HTTP adapter to post the data to it. Whenever XI will post a XML data to a HTTP resource , it will post it as the request body and that is why the code in one of my previous post reads,
    BufferedReader brin =new BufferedReader(new InputStreamReader(request.getInputStream()));
    String inputLine;
    StringBuffer sBuf = new StringBuffer();
    PrintWriter out = response.getWriter();
    response.setContentType("text/xml");
    while ((inputLine = brin.readLine()) != null)
    sBuf.append(inputLine);
    out.println(sBuf.toString());
    brin.close();
    out.flush();
    If you 've noticed, the statement
    request.getInputStream()
    retrieves the body of the request as binary data using a ServletInputStream.
    So your answer to your question is
    <b>XI transferes data to a servlet as a part of HTTP request body</b>, if you use a HTTP adapter.
    2. By J2EE application , if you mean a server java proxy, then the method whose name matches with that of the Inbound Message interface recieves a parameter , from which you can retrieve the parameters passed by XI. Just check the getters of that object.
    Hope this clears your basic doubts!!!
    Rgds,
    Amol

  • I m not able to create xml file in Java Project

    hi all,
    I have created one java project just to try with Ant Builder. I have created one class inside it. and now i m creating an XML file inside that project.
    But as soon as i try to create the File -> New -> File and give the .xml extention of the file this gives error into the project.
    Will you suggest me the solution for that?
    Thanks in advance.

    Assuming that you are facing this problem in NDS, here is the solution.
    Go to Windows--> Preferences --> WorkBench -->File Associations
    In the File Types list select *.xml
    This will display the default associated XML editor as
    XML Editor(default) in the bottom list box.
    Click on add button near the bottom list box and select Text Editor, click Ok.You will see one more entry in the list box as "Text Editor".
    Select this entry and click on the default button.
    Click Ok and close the preferences dialogue.
    Now create a new xml file.You wont see the error this time.
    Please note that this will treat all simple xml files you will create as TEXT Files and always open with Text Editor.You can override this behaviour with right click on the file and select appropriate editor from the "Open With" context menu.
    The error you are talking about is because the XML editor tries to check well-formedness and basic syntax rules for the file that you newly created, actually is a noce feature of the IDE.
    Rgds,
    Amol

  • Writing an XML file using a Servlet

    Hello, I'm trying to code a servlet that receives a POST from a HTTP and output its data to a XML file, the problem is that I get the following error:
    The XML page cannot be displayed
    Cannot view XML input using style sheet. Please correct the error and then click the Refresh button, or try again later.
    XML document must have a top level element. Error processing resource 'http://localhost:8080/XMLSender/xmlsend'.
    I don't know what happens, because I'm NOT trying to show the content, just to save it, I post my code here so anyone can help me, please. Thanks in advance.
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class xmlsender extends HttpServlet
    public void service(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    ServletOutputStream salida = res.getOutputStream();
    res.setContentType("text/xml");
    String cadenanumero = req.getParameter("numero");
    String cadenaoperadora = req.getParameter("operadora");
    String cadenabody = req.getParameter("mensaje");
    String cadenashortcode = req.getParameter("shortcode");
    File f1 = new File("salida.xml");
    FileWriter writer = new FileWriter(f1);
    writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    writer.write("<root>");
    writer.write("<tlf>" + cadenanumero + "</tlf>");
    writer.write("<op>" + cadenaoperadora + "</op>");
    writer.write("<sc>" + cadenashortcode + "</sc>");
    writer.write("<body>" + cadenabody + "</body>");
    writer.write("</root>");
    writer.close();
    }

    Yes, in fact what I want is the file to be in the server, now, I modificated my code to the following:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class xmlsender extends HttpServlet
    public void service(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    ServletOutputStream salida = res.getOutputStream();
    res.setContentType("text/HTML");
    String cadenanumero = req.getParameter("numero");
    String cadenaoperadora = req.getParameter("operadora");
    String cadenabody = req.getParameter("mensaje");
    String cadenashortcode = req.getParameter("shortcode");
    File f1 = new File ("salida.xml");
    FileWriter writer = new FileWriter(f1);
    /*salida.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    salida.println("<root>");
    salida.println("<tlf>" + cadenanumero + "</tlf>");
    salida.println("<op>" + cadenaoperadora + "</op>");
    salida.println("<sc>" + cadenashortcode + "</sc>");
    salida.println("<body>" + cadenabody + "</body>");
    salida.println("</root>"); */
    salida.println("Finalizado");
    f1.createNewFile();
    writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    writer.write("<root>");
    writer.write("<tlf>" + cadenanumero + "</tlf>");
    writer.write("<op>" + cadenaoperadora + "</op>");
    writer.write("<sc>" + cadenashortcode + "</sc>");
    writer.write("<body>" + cadenabody + "</body>");
    writer.write("</root>");
    writer.close();
    It still do not create my file "salida.xml", still don't know why. Any help is welcome.

Maybe you are looking for