Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: XML with SAX

  1. #1
    Junior Member
    Join Date
    May 2009
    Location
    Rochester, NY
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default XML with SAX

    Greetings all! I have a brief question about parsing an XML document using SAX and DOM. I have an XML document with a structure like this...

    <Holidays>
       <Carrier>
          <name>Company 1</name> 
          <interval>5</interval> 
       </Carrier>
       <Carrier>
          <name>company 2</name> 
          <interval>7</interval> 
          <Holiday>
             <Name>Thanksgiving 2009</Name> 
             <Date>11/26/2009</Date> 
          </Holiday>
          <Holiday>
             <Name>Christmas 2009</Name> 
             <Date>12/25/2009</Date> 
          </Holiday>
       </Carrier>
    </Holidays>

    Not all <Carrier> observe a <Holiday>.. What I am trying to do is get all the <Holiday>s for the <Carrier> that I specify. Do I need to reconstruct my XML or can it be done with the format it is in now?

    When I try to get <Date> I end up getting all dates in the entire file, not just the ones that match my specified <Carrier>.
    --
    DewBoy3d
    Rochester, NY


  2. #2
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: XML with SAX

    I wrote this little snippet for you.

    import java.io.File;
    import java.io.IOException;
    import java.util.List;
     
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.JDOMException;
    import org.jdom.input.SAXBuilder;
    import org.jdom.output.Format;
    import org.jdom.output.XMLOutputter;
     
    public class SaxParsing {
     
        @SuppressWarnings("unchecked")
        public static void main(final String... arguments) throws JDOMException, IOException {
            final SAXBuilder builder = new SAXBuilder();
            final Document document = builder.build(new File("c:/holidays.xml"));
     
            System.out.println("-----------------------------------------------------------------------");
            System.out.println("Printing the XML document");
            System.out.println("-----------------------------------------------------------------------");
            System.out.println(new XMLOutputter(Format.getPrettyFormat()).outputString(document));
            System.out.println("");
            System.out.println("-----------------------------------------------------------------------");
     
            final Element rootElement = document.getRootElement();
     
            if (rootElement != null) {
                final List<Element> carrierElements = rootElement.getChildren("Carrier");
     
                if (carrierElements != null && !carrierElements.isEmpty()) {
                    for (final Element carrierElement : carrierElements) {
                        if (carrierElement != null) {
                            final List<Element> holidayElements = carrierElement.getChildren("Holiday");
     
                            if (holidayElements != null && !holidayElements.isEmpty()) {
                                for (final Element holidayElement : holidayElements) {
                                    if (holidayElement != null) {
                                        System.out.println("");
                                        System.out.println("Found Holiday with " + carrierElement.getChildText("name"));
                                        System.out.println("Name: " + holidayElement.getChildText("Name"));
                                        System.out.println("Date: " + holidayElement.getChildText("Date"));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    Hope that helps

    // Json
    Last edited by Json; October 5th, 2009 at 04:21 AM.

  3. #3
    Junior Member
    Join Date
    May 2009
    Location
    Rochester, NY
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: XML with SAX

    JSon,

    Thanks for the reply. I had a litle trouble getting it to work but looks like this is going to work much better that the mess I was trying to create. Thanks again.
    Last edited by dewboy3d; October 4th, 2009 at 08:43 PM.
    --
    DewBoy3d
    Rochester, NY

  4. #4
    Junior Member
    Join Date
    May 2009
    Location
    Rochester, NY
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: XML with SAX

    Now that I have this part working I've been thinking about how to setup the objects. I'm hoping that there is a better way. Currently I have an object Carriers and an object Carrier.

    Carriers is setup like this...
    package org.me.orderentry;
     
    import java.applet.Applet;
    import java.io.IOException;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.JDOMException;
    import org.jdom.input.SAXBuilder;
     
    public class Carriers {
        private ArrayList<Carrier> carriers = new ArrayList<Carrier>();
        private Applet applet;
        private String carrierList;
     
        public Carriers(Applet a) {
            applet = a;
            carrierList = "";
            setCarriers();
        }
     
        public ArrayList<Carrier> getCarriers() {
            return carriers;
        }
     
        public Carrier getCarrier(int index) {
            return carriers.get(index);
        }
     
        @SuppressWarnings("unchecked")
        public void setCarriers() {
            URL url;
            try {
                url = new URL(applet.getCodeBase(), "/orderentrytoolkit/carriers_xml");
     
                final SAXBuilder builder = new SAXBuilder();
                final Document document = builder.build(url.openStream());
     
                final Element rootElement = document.getRootElement();
     
                if (rootElement != null) {
                    final List<Element> carrierElements = rootElement.getChildren("Carrier");
     
                    if (carrierElements != null && !carrierElements.isEmpty()) {
                        for (final Element carrierElement : carrierElements) {
                            if (carrierElement != null) {
                                carriers.add(new Carrier(applet, carrierElement.getChildText("Name")));
                            }
                        }
                    }
                }
            } catch (IOException err) {
                err.printStackTrace();
            } catch (JDOMException err) {
                err.printStackTrace();
            }
        }
    }

    and carrier is setup like this...
    package org.me.orderentry;
     
    import java.applet.Applet;
    import java.io.IOException;
    import java.net.URL;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
     
    import java.util.Date;
    import java.util.List;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.JDOMException;
    import org.jdom.input.SAXBuilder;
     
    public class Carrier {
     
        Applet applet;
        private String name;
        private int interval;
        private ArrayList<String> holidays = new ArrayList<String>();
        SimpleDateFormat formatter;
     
        public Carrier(Applet a, String newName) {
            applet = a;
            name = newName;
            interval = 0;
            formatter = new SimpleDateFormat("MM/dd/yyyy");
            setCarrier();
        }
     
        public void setName(String newValue) {
            name = newValue;
        }
     
        public String getName() {
            return name;
        }
     
        public void setInterval(int newValue) {
            interval = newValue;
        }
     
        public int getInterval() {
            return interval;
        }
     
        public boolean isHoliday(Date date) {
            String tmpDate = formatter.format(date);
            if (holidays.contains(tmpDate)) {
                return true;
            } else {
                return false;
            }
        }
     
        public ArrayList<String> getHolidays() {
            return holidays;
        }
     
        @SuppressWarnings("unchecked")
        public void setCarrier() {
            URL url;
            try {
                url = new URL(applet.getCodeBase(), "/orderentrytoolkit/carriers_xml");
     
                final SAXBuilder builder = new SAXBuilder();
                final Document document = builder.build(url.openStream());
     
                final Element rootElement = document.getRootElement();
     
                if (rootElement != null) {
                    final List<Element> carrierElements = rootElement.getChildren("Carrier");
     
                    if (carrierElements != null && !carrierElements.isEmpty()) {
                        for (final Element carrierElement : carrierElements) {
                            if (carrierElement != null) {
                                if (name.equals(carrierElement.getChildText("Name"))) {
                                    interval = Integer.parseInt(carrierElement.getChildText("Interval"));
     
                                    final List<Element> holidaysElements = carrierElement.getChildren("Holidays");
                                    if (holidaysElements != null && !holidaysElements.isEmpty()) {
                                        for (final Element holidaysElement : holidaysElements) {
                                            final List<Element> holidayElements = holidaysElement.getChildren("Holiday");
     
     
                                            if (holidayElements != null && !holidayElements.isEmpty()) {
                                                for (final Element holidayElement : holidayElements) {
                                                    if (holidayElement != null) {
                                                        holidays.add(holidayElement.getChildText("Date"));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (IOException err) {
                err.printStackTrace();
            } catch (JDOMException err) {
                err.printStackTrace();
            }
        }
    }

    I suppose my question is if ArrayList is ok to use in this case or if I should try a different approach. I'd like to have instances of the Carrier object with the name of the carrier (ex: Carrier1) and the carriers object holding all of those so I can do something like carriers.Carrier18.getInterval() but I just cant figure out how to get instances named (thats the reason i used ArrayList). I use the arraylist to populate a jComboBox so the list is always in the same order as the carriers are. That way I can do carriers.getCarrier(jComboBox.getSelectedIndex()). getInterval() and not worry about indexes being out of sync.

    Anyway, if someone has a better idea, I'd sure like to hear what you have to say. Thanks
    --
    DewBoy3d
    Rochester, NY

  5. #5
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: XML with SAX

    You could of course use a map for this.

        final Map<String, Carrier> carriers = new HashMap<String, Carrier>();
     
        public void addCarrier() {
            carriers.put(carrier.getName(), carrier);
        }

    So whenever you add a carrier to the map you use the carriers name as a key, however if there two carriers of the same name this might not work the way you want it.

    Later on you can then get the carrier out of the map using its name.

        final Carrier carrier = carriers.get("Carrier18");
        carrier.getInterval();

    Hope that helps

    // Json

  6. #6
    Junior Member
    Join Date
    May 2009
    Location
    Rochester, NY
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: XML with SAX

    JSon,

    Thanks again for the quick reply. I had been thinking about this last night some more and was unable to post. I don't think my application should ever know the actual names of the carriers. I am designing it to be used across multiple divisions and the carriers will be different for each. Maps will be new for me and I am definitely going to see how it works out. I did not know any java at all before starting this project so it's all been one big learning experience.

    You said "you could of course" in your reply. Does that mean you think my original solution was wrong and a map is a better solution or is it just an alternative. As I learn, I am trying to get better. this type of feedback helps immensely. Thanks again.
    --
    DewBoy3d
    Rochester, NY

  7. #7
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: XML with SAX

    Its an alternative as I'm not fully aware of the design and requirements of your project.

    A list will at the end of the day always just be a list, however a map will is a list where you specifically tell it what the key to each item will be, so instead of just having indexes 0,1,2... etc you can query for an item in the map using a String, Integer, Double, or any other custom made class you wish to use as a key. Please note though that if you use your own class for the key in the map you should make sure you implement/override the methods hashCode and equals.

    // Json