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 " +
    doc.getDocumentElement().getNodeName());


    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 : " +
    ((Node)textFNList.item(0)).getNodeValue().trim());

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

    NodeList textLNList = lastNameElement.getChildNodes();
    System.out.println("Last Name : " +
    ((Node)textLNList.item(0)).getNodeValue().trim());

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

    NodeList textAgeList = ageElement.getChildNodes();
    System.out.println("Age : " +
    ((Node)textAgeList.item(0)).getNodeValue().trim());

    //------


    }//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
    <book>
    <person>
    <first>Kiran</first>
    <last>Pai</last>
    <age>22</age>
    </person>
    <person>
    <first>Bill</first>
    <last>Gates</last>
    <age>46</age>
    </person>
    <person>
    <first>Steve</first>
    <last>Jobs</last>
    <age>40</age>
    </person>
    </book>

    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
    1. Advertisements

  2. Eric Sosman Guest

    On 5/28/2014 9:04 AM, wrote:
    > 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.
    > [... code snipped; see up-thread ...]


    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
    d
     
    Eric Sosman, May 28, 2014
    #2
    1. Advertisements

  3. markspace Guest

    On 5/28/2014 6:04 AM, wrote:
    > 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.


    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
    #3
  4. Stefan Ram Guest

    writes:
    >write the below program without hardcoding "person"
    >public static void main (String argv [])
    >doc.getElementsByTagName("person");


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

    On Wed, 28 May 2014 06:04:12 -0700 (PDT), wrote:

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


    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

    --
    Ich lese meine Emails nicht, replies to Email bleiben also leider
    ungelesen.
     
    Joerg Meier, May 29, 2014
    #5
  6. markspace Guest

    On 5/28/2014 3:13 PM, Stefan Ram wrote:
    > writes:
    >> write the below program without hardcoding "person"
    >> public static void main (String argv [])
    >> doc.getElementsByTagName("person");

    >
    > doc.getElementsByTagName( argv[ 0 ]);
    >



    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.

    SAX:
    - ContentHandler.startElement:

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

    - Attributes.getLocalName():
    http://docs.oracle.com/javase/7/docs/api/org/xml/sax/Attributes.html#getLocalName(int)

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

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.
Similar Threads
  1. =?Utf-8?B?Sm9l?=

    SelectNodes vs. GetElementsByTagName

    =?Utf-8?B?Sm9l?=, Nov 2, 2005, in forum: ASP .Net
    Replies:
    2
    Views:
    42,713
    =?Utf-8?B?Sm9l?=
    Nov 2, 2005
  2. mynamehere
    Replies:
    0
    Views:
    718
    mynamehere
    Dec 14, 2003
  3. Danny
    Replies:
    1
    Views:
    601
    wooks
    Jul 23, 2004
  4. Ragnar Heil
    Replies:
    5
    Views:
    8,435
    Ragnar Heil
    Apr 27, 2005
  5. Simon Dahlbacka

    xml getElementsByTagName w/o recursion?

    Simon Dahlbacka, Feb 11, 2004, in forum: Python
    Replies:
    2
    Views:
    1,954
    Chris Herborth
    Feb 11, 2004
  6. Max
    Replies:
    1
    Views:
    779
    Martin Honnen
    Aug 9, 2006
  7. =?Utf-8?B?RWFnbGVSZWRASGlnaEZseWluZ0JpcmRzLmNvbQ==

    What Happened to getElementsByTagName in ASP.NET 2.0 Javascript?

    =?Utf-8?B?RWFnbGVSZWRASGlnaEZseWluZ0JpcmRzLmNvbQ==, Mar 8, 2007, in forum: ASP .Net
    Replies:
    3
    Views:
    2,045
    Mark Rae
    Mar 8, 2007
  8. Replies:
    1
    Views:
    673
    Stefan Behnel
    Nov 20, 2007
Loading...