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!

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

  • How i can store a DOM Tree to XML file

    I want to insert a xml documet into another another xml document and then store it.
    for this i have parsed a xml document using com.sun.xml.parser and got its domtree in document doc1 by builder.getDocument(). After that i parsed another xml document and got it's domtree in document doc2 by builder.getDocument().
    now i created a Document type doc . I create dom tree in doc that contains all the nodes of doc1 and insert the doc2 at a position . If i m printing this doc i got the required document. Now i want to store this doc into a xml file. so i paas thid doc and filename in which i want to store it into a function
    public static void writeXmlToFile(String filename, Document document)
    try
                   // Prepare the DOM document for writing
         Source source = new DOMSource(document);
         // Prepare the output file
         File file = new File(filename);
         Result result = new StreamResult(file);
    // Write the DOM document to the file
         // Get Transformer
         Transformer xformer = TransformerFactory.newInstance().newTransformer();
              // Write to a file
         xformer.transform(source, result);
    catch (TransformerConfigurationException e)
         System.out.println("TransformerConfigurationException: " + e);
    catch (TransformerException e)
         System.out.println("TransformerException: " + e);
    but i m getting following error
    Exception in thread "main" java.lang.AbstractMethodError: com.sun.xml.tree.ElementNode.getNamespacesURI()Ljava/lang/String;
    at com.sun.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)
    at com.sun.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)
    at com.sun.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)
    at com.sun.apache.xalan.internal.xsltc.trax.TranformerImpl.transformIdentity(Unknown Source)
    at com.sun.apache.xalan.internal.xsltc.trax.TranformerImpl.transformIdentity(Unknown Source)
    at com.sun.apache.xalan.internal.xsltc.trax.TranformerImpl.transformIdentity(Unknown Source)

    thanks for the reply
    i m able to do my job using
    import javax.xml.parsers.*;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder1 = factory.newDocumentBuilder();
         doc = builder1.parse(uri);
    when i want to covert this doc into an xml file by passing this doc in the function below then it is ok..
    public static void writeXmlToFile(String filename, Document document)
    try
    // Prepare the DOM document for writing
    Source source = new DOMSource(document);
    // Prepare the output file
    File file = new File(filename);
    Result result = new StreamResult(file);
    // Write the DOM document to the file
    // Get Transformer
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    // Write to a file
    xformer.transform(source, result);
    catch (TransformerConfigurationException e)
    System.out.println("TransformerConfigurationException: " + e);
    catch (TransformerException e)
    System.out.println("TransformerException: " + e);
    but i want to use com.sun.xml.parser like
    import com.sun.xml.parser.*;
    import com.sun.xml.tree.XmlDocumentBuilder;
    XmlDocumentBuilder builder = new XmlDocumentBuilder();
    Parser parser = new com.sun.xml.parser.Parser();
    parser.setDocumentHandler(builder);
    builder.setParser(parser);
    builder.setDisableNamespaces(false);
    parser.parse(uri);
    doc = builder.getDocument();
    when i m trying to store this doc into an xml file by passing this doc into funtion writeXmlToFile( filename, doc) then the errors occur (that i hav told in the first post)
    plz help..

  • How to convert DOM Tree in XML File

    Hi there,
    I am successful to build a DOM tree in memory where i am adding elements. Now after all this i want to make a XML file of that DOM representation. Now, i am confused with my code that how to transfer DOM structure to xml file ? A small code is attached herewith ?
    doc = db.newDocument();
                   doc.normalizeDocument();
                   doc.setXmlVersion("1.0");
                   doc.createComment("Created By: Sachin Kulkarni");
                   Element rn = doc.createElement("RootNode");
                   Element n1 = doc.createElement("A1");
                   ((Node)n1).setNodeValue("Element A1");
                   Element n11 = doc.createElement("A11");
                   ((Node)n11).setNodeValue("Element A11");
                   Element n12 = doc.createElement("A12");
                   ((Node)n12).setNodeValue("Element A12");
                   ((Node)n1).appendChild( ((Node)n11) );
                   ((Node)n1).appendChild( ((Node)n12) );
                   Element n2 = doc.createElement("A2");
                   ((Node)n2).setNodeValue("Element A2");
                   Element n3 = doc.createElement("A3");
                   ((Node)n3).setNodeValue("Element A3");
                   ((Node)rn).appendChild( ((Node)n1) );
                   ((Node)rn).appendChild( ((Node)n2) );
                   ((Node)rn).appendChild( ((Node)n3) );
    //creating the xml file
                   Source source = new DOMSource((Element) doc.getElementsByTagName("RootNode").item(0));
                   StringWriter out = new StringWriter();
                   StreamResult result = new StreamResult(out);
                   Transformer transformer = TransformerFactory.newInstance().newTransformer();
                   transformer.setOutputProperty("encoding", "iso-8859-1");
                   transformer.setOutputProperty("indent", "yes");
                   //transformer.setOutputProperty("test.xml","1");
                   //transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
                   transformer.transform(source,result);
                   result.getWriter().toString();
    ==================
    Is it any problem with the implementation ? How to use fileoutputstream with this ?

    I have done like this:
    DocumentBuilderFactory docBuildFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = docBuildFactory.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element root = (Element)doc.createElement("Root");
    doc.appendChild(root);
    Element address = (Element)doc.createElement("Address");
    address.appendChild((Element)doc.createElement("Street"));
    address.appendChild((Element)doc.createElement("PostCode"));
    address.appendChild((Element)doc.createElement("Town"));
    Element country = (Element)doc.createElement("Country");
    country.setAttribute("type","EU");
    Text cname = doc.createTextNode("Spain");
    country.appendChild(cname);
    address.appendChild(country);
    root.appendChild(address);
    TransformerFactory tranFactory = TransformerFactory.newInstance();
    Transformer aTransformer = tranFactory.newTransformer();
    aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
    Source src = new DOMSource(doc);
    Result dest = new StreamResult(new FileOutputStream(new File("test.xml")));
    aTransformer.transform(src, dest);

  • Java tree to xml

    Hi,
    I want to create an xml code from a java tree. I'm reading the tree data from DB and have a class named Node. For each node, setting data of Node class object.Is there anyone knows how to handle this.
    P.S: I just need a converter that converts the tree in the DB to XML

    Create a tree walker that generates SAX events appropriate to the data in the Node.
    Pass those events to something else (an XMLWriter http://www.megginson.com/Software/ to generate text directly, or a SAXSource to transform it to DOM or text), to generate the XML.
    Eg:import javax.xml.transform.*;
    import javax.xml.transform.sax.SAXSource;
    import javax.xml.transform.stream.StreamResult;
    import org.xml.sax.SAXException;
    import org.xml.sax.InputSource;
    import org.xml.sax.helpers.AttributesImpl;
    import org.xml.sax.helpers.XMLFilterImpl;
    import java.util.*;
    // dummy Node class
    class Node {
      final String name;
      final List children = new ArrayList();
      Node (String name) { this.name = name; }
      Node append (Node child) { children.add(child); return this; }
    class NodeWalker extends XMLFilterImpl {
      // root of tree to walk
      final Node root;
      public NodeWalker (Node root) {
        this.root = root;
      public void parse (InputSource input) throws SAXException {
        startDocument();
        try {
          visit(root);
        } finally {
          endDocument();
      // recursively visit the node and its children
      void visit (Node node) throws SAXException {
        AttributesImpl attributes = new AttributesImpl();
        attributes.addAttribute("", "name", "name", "CDATA", node.name);
        startElement("", "node", "node", attributes);
        for (Iterator childIt = node.children.iterator(); childIt.hasNext(); ) {
          visit((Node)childIt.next());
        endElement("", "node", "node");
    public class NodeWalkerTest {
      static Node node (String name) { return new Node(name); }
      public static void main (String[] args) {
        try {
          // set up some nodes
          final Node root = node("root").
            append(node("one")).
            append(node("two").
                   append(node("alpha")).append(node("beta")).
                   append(node("gamma")).append(node("delta"))).
            append(node("three"));
          // transform them to a stream result,
          final TransformerFactory factory = TransformerFactory.newInstance();
          final Transformer nullTransform = factory.newTransformer();
          nullTransform.transform(new SAXSource(
            // SAX source created using node walker and default input source
            new NodeWalker(root), new InputSource()),
            new StreamResult(System.out));
        } catch (Exception ex) {
          ex.printStackTrace(System.out);
    }Pete

  • 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.

  • 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;

  • Saving a Rendered tree as XML file

    I am making a gui mainly based on jtrees. One tree i created adding defaulttreenodes. This I am able to save as XML code and retrieve also.
    Another tree, I made by rendering its node as Jtable. But this tree I am not able to save as XML as the one before.
    It gives Instantiation Exception error. Can anybody say the reason and give an alternative method for saving and retrieiving ?

    Quadruple-posting. If you want to answer lets keep the discussion in this posting:
    [http://forum.java.sun.com/thread.jspa?threadID=5282364]
    If you want help in the future, I suggest you learn how to use the forum properly. That means a single posting. If you make a mistake you can always reply to your posting stating you made a mistake.

  • 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

  • How can i write the DOM tree to the XML File?

    Asslamo ala mn etb3a Alhoda.
    My problem priefly is that i can't write the DOM tree to XML file.
    I write following code to give the user the ability to input the name of data base which he want to create.
    If i wrote DB name,its atrributes and its values succefully to XML file ,then i'll read it succefully to RAM.
    It'll be simple DBMS.
    ***My code***
    import javax.swing.*;
    import javax.xml.parsers.*;
    import org.w3c.dom.Document;
    import org.w3c.dom.DOMException;
    import org.w3c.dom.Element;
    public class Main {
         * @param args
    public static void main(String[] args) {
         // TODO Auto-generated method stub     
         String DBname;
    DBname=JOptionPane.showInputDialog("Enter Your Data Base Name");
    OPerations O=new OPerations();
         O.creatDB(DBname);
    class OPerations {
    public void creatDB(String name){
         //get an empty Document
         DocumentBuilderFactory f; f=DocumentBuilderFactory.newInstance();
         try {
              builder = f.newDocumentBuilder();
              Document doc= builder.newDocument();
         //Build tree DOM With the root Node
              Element root=doc.createElement(name);
         //add the root element to thevdocument
              doc.appendChild(root);
    catch (ParserConfigurationException e) {
         // TODO Auto-generated catch block
              e.printStackTrace();
    }

    Do an identity transformation to output it:TransformerFactory tf = TransformerFactory.newInstance();
    Transformer tr = tf.newTransformer();
    tr.transform(new DOMSource(doc), new StreamResult(new FileOutputStream(new File(filename))));(typed without syntax check)

  • 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

  • DocumentBuilder parser, DOM doucment object from a XML file error

    Hi guys
    I created a program which parses a xml and creates a DOM document object from
    it. The parser is validating.
    class xmlParser
        //create arrylist to store employee in
        private ArrayList<Employee> employeeStore = new ArrayList<Employee>();
        private DocumentBuilder parser;
        private static Document document;     
        //create an instant of Employee to be added to the arraylist
        private Employee theEmployee = new Employee();
        //create an instant of Address to be added to Employee to again be
        //added to Employee
        private Address employeeAddress = new Address();
        public xmlParser()
        public xmlParser(String myfile) throws IOException 
              //validate the XML document agaisnt the given dtd
              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              factory.setValidating(true);
              factory.setIgnoringElementContentWhitespace(true);
              try {
                  parser = factory.newDocumentBuilder();
              }catch(javax.xml.parsers.ParserConfigurationException d) {
                   System.out.println("error with new document builder");
              //create document object (DOM tree) from xml file
              try {
                  document = parser.parse(new File(myfile));
              }catch(org.xml.sax.SAXException e) {
                  System.out.println("Error with parser file still creating xml personnel2");
        } In my main method when i call:
    xmlParser parsertree = new xmlParser("personnel.xml"); the exception keeps getting thrown and i get my my message back "Error with parser file still creating xml personnel2"
    Can't seem to figure it out, any ideas would be great.
    Thanks alot

    Hi,
    A - Check that the xml file is located in the same directory where you
    run your app.
    B - Check that the xml file is correct (in XML way).
    Suggestion : you may print the exception message, it might help.
    Hope that help,
    Jack

Maybe you are looking for