Eloquence Denied?: getElementsByTagName

C

clusardi2k

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

*/
 
E

Eric Sosman

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

markspace

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

Stefan Ram

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

doc.getElementsByTagName( argv[ 0 ]);
 
J

Joerg Meier

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
 
M

markspace

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

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top