Eloquence Denied?: getElementsByTagName

Discussion in 'Java' started by clusardi2k@aol.com, May 28, 2014.

  1. Guest

    Is there an alternative way to write the below program without hardcoding "person", "first", "last", and "age" or putting these into a file and reading the contents of a file.

    Thank you,

    import java.io.File;
    import org.w3c.dom.Document;
    import org.w3c.dom.*;

    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;

    public class ReadAndPrintXMLFile{

    public static void main (String argv []){
    try {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.parse (new File("book.xml"));

    // normalize text representation
    doc.getDocumentElement ().normalize ();
    System.out.println ("Root element of the doc is " +

    NodeList listOfPersons = doc.getElementsByTagName("person");
    int totalPersons = listOfPersons.getLength();
    System.out.println("Total no of people : " + totalPersons);

    for(int s=0; s<listOfPersons.getLength() ; s++){

    Node firstPersonNode = listOfPersons.item(s);
    if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){

    Element firstPersonElement = (Element)firstPersonNode;

    NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
    Element firstNameElement = (Element)firstNameList.item(0);

    NodeList textFNList = firstNameElement.getChildNodes();
    System.out.println("First Name : " +

    NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
    Element lastNameElement = (Element)lastNameList.item(0);

    NodeList textLNList = lastNameElement.getChildNodes();
    System.out.println("Last Name : " +

    NodeList ageList = firstPersonElement.getElementsByTagName("age");
    Element ageElement = (Element)ageList.item(0);

    NodeList textAgeList = ageElement.getChildNodes();
    System.out.println("Age : " +


    }//end of if clause

    }//end of for loop with s var

    }catch (SAXParseException err) {
    System.out.println ("** Parsing error" + ", line "
    + err.getLineNumber () + ", uri " + err.getSystemId ());
    System.out.println(" " + err.getMessage ());

    }catch (SAXException e) {
    Exception x = e.getException ();
    ((x == null) ? e : x).printStackTrace ();

    }catch (Throwable t) {
    t.printStackTrace ();
    //System.exit (0);

    }//end of main



    XML File

    Program Output

    Root element of the doc is book
    Total no of people : 3
    First Name : Kiran
    Last Name : Pai
    Age : 22
    First Name : Bill
    Last Name : Gates
    Age : 46
    First Name : Steve
    Last Name : Jobs
    Age : 40

    , May 28, 2014
    1. Advertisements

  2. Eric Sosman Guest

    I can't think of any. You can certainly navigate the DOM without
    foreknowledge of the tag names, but that won't tell you what to do
    with each tag. That is, there's nothing in the XML itself to tell you
    to count the number of `person' tags, nor to print "Last Name : " before
    the content of each `last' tag. For that matter, there's nothing in
    the XML that tells your program to ignore the `citizenship' tags.

    To put it another way: The XML data doesn't know which parts of
    itself your program might be interested in, nor what your program
    should do with them. It's up to your program to know these things.
    Eric Sosman, May 28, 2014
    1. Advertisements

  3. markspace Guest

    I don't think I understand the question. What does "hard coding" refer
    to here?

    If by "hard code" you mean the fields themselves then an ArrayList or
    Stack can help you out. I've done that with XML, it works fine.

    OTOH, at some point, if you want values to appear in a program, you have
    to code them in. Data entry is a thing. Sometimes you can outsource
    this to someone else, but in my experience outsourced data entry makes a
    lot of errors and pretty much typifies "lowest cost solution."

    Sometimes you can generate data procedurally. Ie calculate the vales.
    Works best for making test data imo.

    Sometimes you can buy a database or find a similar project and use their
    database. There's a fair amount of free stuff available online.

    Leif raises a good point that you have to interpret the data at some
    point. If you XML has a schema however you should be able to write (or
    download, because it's a generic thing) a parser that reads both the XML
    and the schema and then interprets the data in a generic but more
    meaningful way.
    markspace, May 28, 2014
  4. Stefan Ram Guest

    doc.getElementsByTagName( argv[ 0 ]);
    Stefan Ram, May 28, 2014
  5. Joerg Meier Guest

    Isn't there an Annotation/Bean based way to use XML ? That way, you would
    just need field names corresponding to the XML.

    Liebe Gruesse,
    Joerg Meier, May 29, 2014
  6. markspace Guest

    Oh, if *that's* what the OP means... hmm, I usually use SAX, I'm not
    seeing a DOM equivalent. SAX hands you the name of the node, and lists
    attributes by index (number) rather than strictly by name. I guess DOM
    is for when you already know that there's going to be a "person" node in
    your XML file.

    - ContentHandler.startElement:

    http://docs.oracle.com/javase/7/doc...ng, java.lang.String, org.xml.sax.Attributes)

    - Attributes.getLocalName():

    and other similar methods that take an int index like getQName()
    and getValue().
    markspace, May 29, 2014
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.