XML

"Continuous effort - not strength or intelligence - is the key to unlocking our potential." ==> Winston Churchill

Name:
Location: Bangalore, India

Friday, March 24, 2006

Whats the difference in getElementsByTagName(String str)

Whats the difference between

getElementsByTagName(String str) of Document object and
getElementsByTagName(String str) of Element object.


Sample XML Document.

<scenariotemplate>
   <layout name="intro,quest,conc" width ="1" height="3">
      <textElement name="Introduction" position="1"></textElement>
      <listElement name="Questions" position="2"></listElement>
      <textElement name="Conclusion" position="3"></textElement>
   </layout>
</scenariotemplate>

A sample Program:

Document doc = null;
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();

try {
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
doc = docBuilder.parse(new File("component.xml"));
}catch(ParserConfigurationException e1) {
}catch(SAXException e2) {
}catch(IOException e3) {
}

/* Scenario I */
Element RootElement = doc.getDocumentElement();
NodeList templates = RootElement.getElementsByTagName("*");

/* Scenario II */
NodeList templates = doc.getElementsByTagName("*");

int totaltemplates = templates.getLength();
System.out.println("Total no of child elements : " + totaltemplates);

In Scenario I - OUTPUT will be
Total no of child elements : 4
This is excluding the ROOT element.

In Scenario II - OUTPUT will be
Total no of child elements : 5
This is including the ROOT element.

0 Comments:

Post a Comment

<< Home