Send a suggestion!

We're building a brand new version of the site, and we'd love to hear your ideas

Members

Technology Zones

IBM Learning Center

Articles

Hosted By

MaximumASP

Info

[2064] A simple way to read an XML file in Java

Last post 08-30-2008 4:12 PM by KPRao. 31 replies.
Page 2 of 3 (32 items) < Previous 1 2 3 Next >
Sort Posts: Previous Next
  • 01-13-2006 9:42 AM In reply to

    Generic Code for XML Required

    Hi There
    the code you have given for xml parsing is really superb can you give me a generic code for parsing any xml file given i will be really thankfull if you can mail me that code at deepsingh_mca@yahoo.com
    • Post Points: 0
  • Advertisement

    • Red Gate Software

    Advertisement

    Want to boost your .NET application performance?

    Some developers always seem to write efficient and lightening-fast code. What is their secret? It’s ANTS Profiler. “We improved the performance of the application up to 10 times” Dan Ports, Intrigma.

    Try it for yourself now.

  • 01-31-2006 9:56 AM In reply to

    • Jkin
    • Not Ranked
    • Joined on 01-31-2006
    • New Member
    • Points 10

    how to represent null values in XML

    The code is really great. But I'm facing a problem.
    I have a XML doc like this....
    *****************************************************
    <table>
        <rec>
            <field1>abcd</field1>
            <field2>xyz</field2>
        </rec>
        <rec>
            <field1></field1>
            <field2>kio</field2>
        </rec>
    </table>
    ******************************************************

    When I use your code with some modifications, the first record is displayed correctly, but the second record doesn't appear.

    Also, When I use wordpad to view the contents of XML file, it shows me the exact contents, but when i try to view the content using explorer, in the second rec field, where the value is not there, it shows

    <field1 />

    instead of <field1></field1>



    Can you tell me why this is happening and how can I read a "null" value.
    • Post Points: 10
  • 03-30-2006 4:06 PM In reply to

    • richard0529
    • Not Ranked
    • Joined on 03-29-2006
    • United States
    • New Member
    • Points 5

    Re: [2064] A simple way to read an XML file in Java

    Thank you for such a clear and concise example. I used this to base an XML mining applicaton. Did not need so much of the nesting feature for my particular input, but your code had the following surprises for me. Before using your sample: NodeList - my code wouldn't let me instantiate an abstract class! Element - I had problems casting from Node Document - My parseXmlFile() args and return were incorrect. Thanks again, Richard
    • Post Points: 5
  • 04-25-2006 5:20 AM In reply to

    Re: how to represent null values in XML

    Check your null value.

    Assump that you have null value in Age tag <Age></Age>

    NodeList textAgeList = ageElement.getChildNodes();
                        if (textAgeList.getLength() == 0) {
                            System.out.print("Age : Need more infor of Age \n");
                        } else {
                            System.out.println("Age : " +
                                               ((Node) textAgeList.item(0)).
                                               getNodeValue().trim());
                        }






    • Post Points: 10
  • 04-25-2006 3:03 PM In reply to

    • Supertaff
    • Not Ranked
    • Joined on 04-25-2006
    • United Kingdom
    • New Member
    • Points 10

    Re: how to represent null values in XML

    Hi,

     

    On a similar theme, how would you handle if the node is not actually present in the XML as in the second person below as I'm currently getting an exception from this?

    Do you have to wrap a try/catch around each retrieve from of a node?

     

    e.g.

    <Person>

    <first>Mark></first>

    <last>Thomas</last>

    <age>36</age>

    </Person>

    <Person>

    <first>Fred></first>

    <last>Bloggs</last>

    </Person>

     

    Thanks,

     

    Mark Thomas

     

     

    • Post Points: 10
  • 07-30-2006 1:26 PM In reply to

    • pbk2
    • Not Ranked
    • Joined on 07-30-2006
    • New Member
    • Points 10

    Re: how to represent null values in XML

    Hello Mark,

                         If you have found a solution to your above problem please send me the code. I shall be eagerly waiting.

                            Many thanks,

                                   Prakash

    • Post Points: 5
  • 07-31-2006 12:38 AM In reply to

    • pbk2
    • Not Ranked
    • Joined on 07-30-2006
    • New Member
    • Points 10

    Re: how to represent null values in XML

    Someone please send me code to read the following using Kiran's code

    <Fruit>

    <Type>Apple</Type>

    <Type>Orange</Type>

    <Type>Peach</Type>

    </Fruit>

    Thanks,

           Prakash

    • Post Points: 5
  • 09-23-2006 7:35 AM In reply to

    Re: A simple way to read an XML file in Java

    Hi,

         Thank you for your code. I want to read an XML document that is having different child tags. Here you are using the same name for all  the childs. I need the code for reading an XML document that is having differnt child nodes.

    For example, consider the following code snippet

    <Author>

    -   <Request>

          <Name>

         <Book>

    </Request>

    -<Collection>

         <Colletion_Name>

      . ...</Collection>

    </Author>

    Could you please send me the code for this.It will be very helpful for me.

    Thanks in advance.

    Regards,

    Dhanaprabhu

      

    • Post Points: 5
  • 09-26-2006 12:49 PM In reply to

    How to read an XML file data by giving a specific element value as input

    Hi All,

              How to read an XML  data by giving a particular tag name as input.

    Regards,

    Dhana

    • Post Points: 5
  • 11-24-2006 10:59 AM In reply to

    Re: [2064] A simple way to read an XML file in Java

    How can I retrieve the elements from nested tags. like
    <shop>
        <book>
              <subject>
                    <author>Something</author>
              </subject>
        </book>
    </shop>
    Thanks & Regards
    AbdulMajid










    • Post Points: 5
  • 02-01-2007 12:42 PM In reply to

    Re: A simple way to read an XML file in Java

    please send me the java code if got the solution for ur query i need it urgently reply on palwencha@gmail.com
    • Post Points: 5
  • 02-15-2007 1:55 PM In reply to

    Re: [2064] A simple way to read an XML file in Java

    Its realy nice, i have been searching for that code, now i got it, thanks a lot, and i have one question,  how to read an XML data in ejb? any body can help me, plz send to my mail : sainathgowd@gmail.com, thanks advance.

    Regards

    Sai.

    • Post Points: 5
  • 02-23-2007 6:25 PM In reply to

    Re: [2064] A simple way to read an XML file in Java

    hi
    this is a code written in XML and now i want to read this code in java
    so please help me

    <?xml version="1.0" encoding="UTF-8"?>
    <descriptor>
        <file>
            <name>simple.txt</name>
            <type>TXT</type>
            <delimiter></delimiter>
        </file>

        <table>
            <name>simple</name>
        </table>
       
        <fields>
            <field>
                <name>Date</name>
                <type>date</type>
                <size>8</size>
                <begin_offset>0</beginoffset>
                <end_offset>8</end_offset>
            </field>
           
            <field>
                <name>Phone</name>
                <type>char</type>
                <size>10</size>
                <begin_offset>8</beginoffset>
                <end_offset>18</end_offset>
            </field>
        </fields>
    </descriptor>

    Thanks
    Mayank





































    • Post Points: 5
  • 06-25-2007 10:10 AM In reply to

    Re: [2064] A simple way to read an XML file in Java

    a good way u introduces but

    dear friend

    i have problem to solve this matter plz help me or any body else who know can also mail me on capricorn_4all@hotmail.com

    i have to make a simple window/frame using java swing and create menus at runtime as described in xml document. XML document is attached below i have needed to load and read xml document using Java API xml. This xml document contains the menus structure.

    When we run the application and pass the xml document name using command line argument then the output should contain a window/frame on the screen and create menus as described in the xml document. If we change any menu settings in xml document. Then application should able to recreate menus according to the change.

    Note:

    1.      Use java API for xml processing

    2.      Xml document passed as  command line argument

    All menus will be created at run time as described in the xml document

    The xml file with code is as under for your kind consideration.

     

    so dear if any body can help me so plz mail me with code/help as soon as possible

    With the above line of instructions may i have able to read xml but still not able to create runtime menus by using swing and my desired xml file. plz help me as soon as possible i ll b thank full to u.

    The xml code that i have to use is:

     

    <?xml version="1.0" encoding="UTF-8"?>

    <!-- New document created at Sun Dec 11 20:59:54 GMT+03:00 2005 -->

    <!-- Created by abc -->

    <console>

                <menus type='Main'>

                            <menu name='File'>

                                        <menuitem name='New' />

                                        <menuitem name='Open' />

                                        <menuitem name='Close' />

                                        <menuitem name='Exit' />

                            </menu>

                            <menu name='Search'>

                                        <menuitem name='Find' />

                                        <menuitem name='Find Next' />

                                        <menuitem name='Replace' />

                            </menu>

                            <menu name='Help'>

                                        <menuitem name='Index' />

                                        <menuitem name='About' />

                            </menu>                      

                </menus>

               

                <menus type='Popup'>

                            <menuitem name='Cut' />

                            <menuitem name='Copy' />

                            <menuitem name='Paste' />

                            <menuitem name='Find' />

                </menus>

    </console>

     
    • Post Points: 5
  • 07-23-2007 4:37 PM In reply to

    • aeseeke
    • Not Ranked
    • Joined on 07-23-2007
    • United States
    • New Member
    • Points 5

    Re: [2064] A simple way to read an XML file in Java

    Hey, that code was cool and worked great for me but I'm a n00b at Java and couldn't change it to fit this program I'm trying to get to work.

    I got all this code from a book and it doesn't work right. When I run the application file it gives me a stack trace bser. Did I do something wrong in the code or what? Oh and btw, yes there are other files associated with this but didn't want to list ALL the code since I figure the error's in here.

    import java.util.*;
    import java.io.*;
    import javax.xml.stream.*; //StAX API


    //mine!
    public class ProductXMLFile implements ProductDAO
    {
        private String productsFilename = "products.xml";
        private File productsFile = null;

        public ProductXMLFile()
        {
            productsFile = new File(productsFilename);
        }

        private void checkFile() throws IOException
        {
            //if the file doesn't exist, create it
            if(!productsFile.exists())
                productsFile.createNewFile();
        }

        private boolean saveProducts(ArrayList<Product> products)
        {
            //creates the XMLOutputFactory object
            XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();

            try
            {
                //check the file to make sure it exists
                this.checkFile();

                //creates XMLStreamWriter object
                FileWriter fileWriter = new FileWriter(productsFilename);
                XMLStreamWriter writer = outputFactory.createXMLStreamWriter(fileWriter);

                //write the products to the file
                /*writer.writeStartDocument("1.0");
                writer.writeStartElement("Products");
                for (Product p : products)
                {
                    writer.writeStartElement("Product");
                    writer.writeAttribute("Code", p.getCode());

                    writer.writeStartElement("Description");
                    writer.writeCharacters(p.getDescription());
                    writer.writeEndElement();

                    writer.writeStartElement("Price");
                    double price = p.getPrice();
                    writer.writeCharacters(Double.toString(price));
                    writer.writeEndElement();

                    writer.writeEndElement();
                }
                writer.writeEndElement();
                writer.flush();
                writer.close();
            }
            catch(IOException e)
            {
                e.printStackTrace();
                return false;
            }
            catch(XMLStreamException e)
            {
                e.printStackTrace();
                return false;
            }
            return true;*/
        }

        public ArrayList<Product> getProducts()
        {
            ArrayList<Product> products = new ArrayList<Product>();
            Product p = null;

            //creates the XMLInputFactory object
            /*XMLInputFactory inputFactory = XMLInputFactory.newInstance();

            try
            {
                //check the file to make sure it exists
                this.checkFile();

                //creates a XMLStreamReader object
                FileReader fileReader = new FileReader(productsFilename);
                XMLStreamReader reader = inputFactory.createXMLStreamReader(fileReader);

                //read the products from the file
                while(reader.hasNext())
                {
                    int eventType = reader.getEventType();
                    switch(eventType)
                    {
                        case XMLStreamConstants.START_ELEMENT:
                            String elementName = reader.getLocalName();
                            if(elementName.equals("Products"))
                            {
                                p = new Product();

                                String code = reader.getAttributeValue(0);
                                p.setCode(code);
                            }
                            if(elementName.equals("Description"))
                            {
                                String description = reader.getElementText();
                                p.setDescription(description);
                            }
                            if(elementName.equals("Price"))
                            {
                                String priceString = reader.getElementText();
                                double price = Double.parseDouble(priceString);
                                p.setPrice(price);
                            }
                            break;
                        case XMLStreamConstants.END_ELEMENT:
                            elementName = reader.getLocalName();
                            if(elementName.equals("Product"))
                            {
                                products.add(p);
                            }
                            break;
                        default:
                            break;
                    }
                    reader.next();
                }*/
            }
            catch (IOException e)
            {
                e.printStackTrace();
                return null;
            }
            catch(XMLStreamException e)
            {
                e.printStackTrace();
                return null;
            }
            return products;
        }

        public Product getProduct(String code)
        {
            ArrayList<Product> products = this.getProducts();
            for (Product p : products)
            {
                if (p.getCode().equals(code))
                return p;
            }
            return null;
        }

        public boolean deleteProduct(Product p)
        {
            ArrayList<Product> products = this.getProducts();
            products.remove(p);
            return this.saveProducts(products);
        }

        public boolean addProduct(Product p)
        {
            ArrayList<Product> products = this.getProducts();
            products.add(p);
            return this.saveProducts(products);
        }

        public boolean updateProduct(Product newProduct)
        {
            ArrayList<Product> products = this.getProducts();

            //get the old product and remove it
            Product oldProduct = this.getProduct(newProduct.getCode());
            int i = products.indexOf(oldProduct);
            products.remove(i);

            //add the updated product
            products.add(i, newProduct);

            return this.saveProducts(products);
        }
    }



























































































































































































    • Post Points: 5
Page 2 of 3 (32 items) < Previous 1 2 3 Next >