Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #28574 > unrolled thread

Eloquence Denied?: getElementsByTagName

Started byclusardi2k@aol.com
First post2014-05-28 06:04 -0700
Last post2014-05-28 16:18 -0700
Articles 6 — 5 participants

Back to article view | Back to comp.lang.java.programmer


Contents

  Eloquence Denied?: getElementsByTagName clusardi2k@aol.com - 2014-05-28 06:04 -0700
    Re: Eloquence Denied?: getElementsByTagName Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-05-28 09:50 -0400
    Re: Eloquence Denied?: getElementsByTagName leif.roar@invalid.com (Leif Roar Moldskred) - 2014-05-28 09:24 -0500
    Re: Eloquence Denied?: getElementsByTagName markspace <markspace@nospam.nospam> - 2014-05-28 09:07 -0700
    Re: Eloquence Denied?: getElementsByTagName Joerg Meier <joergmmeier@arcor.de> - 2014-05-29 01:05 +0200
    Re: Eloquence Denied?: getElementsByTagName markspace <markspace@nospam.nospam> - 2014-05-28 16:18 -0700

#28574 — Eloquence Denied?: getElementsByTagName

Fromclusardi2k@aol.com
Date2014-05-28 06:04 -0700
SubjectEloquence Denied?: getElementsByTagName
Message-ID<de4b166f-4b14-4b56-9244-0d4745a64fc4@googlegroups.com>
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

*/

[toc] | [next] | [standalone]


#28576

FromEric Sosman <esosman@comcast-dot-net.invalid>
Date2014-05-28 09:50 -0400
Message-ID<lm4pim$jbv$1@dont-email.me>
In reply to#28574
On 5/28/2014 9:04 AM, clusardi2k@aol.com 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
esosman@comcast-dot-net.invalid

[toc] | [prev] | [next] | [standalone]


#28578

Fromleif.roar@invalid.com (Leif Roar Moldskred)
Date2014-05-28 09:24 -0500
Message-ID<u9udncpw-68XbBjOnZ2dnUVZ8rmdnZ2d@giganews.com>
In reply to#28574
clusardi2k@aol.com 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.
>

No, not really. When you work with structured data, you will have to
define the semantic meaning of the data at some point ("elements with
the name 'person' is _this_ kind of data, elements with the name
'first' is _that_ kind of data") -- either directly in the program 
code or in a configuration layer ("putting these ingo a file".)


In my experience, when you're working with XML your best bet is
usually to just write your parsing code to the particular XML
structure you've got at the moment. Don't try to generalize or
parameterize the parsing code to handle XML data in general -- you'll
just end up "programming in the configuration" and doing twice as much
work.

-- 
Leif Roar Moldskred

[toc] | [prev] | [next] | [standalone]


#28583

Frommarkspace <markspace@nospam.nospam>
Date2014-05-28 09:07 -0700
Message-ID<lm51kq$jnb$1@dont-email.me>
In reply to#28574
On 5/28/2014 6:04 AM, clusardi2k@aol.com 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.

[toc] | [prev] | [next] | [standalone]


#28589

FromJoerg Meier <joergmmeier@arcor.de>
Date2014-05-29 01:05 +0200
Message-ID<13vyrna8v6hka$.u4paph8hswr8.dlg@40tude.net>
In reply to#28574
On Wed, 28 May 2014 06:04:12 -0700 (PDT), clusardi2k@aol.com 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.

[toc] | [prev] | [next] | [standalone]


#28590

Frommarkspace <markspace@nospam.nospam>
Date2014-05-28 16:18 -0700
Message-ID<lm5qsk$ap8$1@dont-email.me>
In reply to#28574
On 5/28/2014 3:13 PM, Stefan Ram wrote:
> clusardi2k@aol.com 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/docs/api/org/xml/sax/ContentHandler.html#startElement%28java.lang.String,%20java.lang.String,%20java.lang.String,%20org.xml.sax.Attributes%29

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

     and other similar methods that take an int index like getQName() 
and getValue().

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.java.programmer


csiph-web