
hi i have a problem.
// this sample code is reading xml file in java
DefaultHandler handler = new DefaultHandler() { boolean name = false;
public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("NAME")) {
name = true;
}
}
public void characters(char ch[], int start, int length)
throws SAXException {
if (name) {
System.out.println("Name: "
+ new String(ch, start, length));
name = false;
}
}
};
in the above example i copmpare qName with NAME. NAME is xml element. but my problem is when xml file change in future then my java code will also change. but is there any chance if an xml element is change my code wil not change.

Try this one.
1)roseindia.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<roseindia>
<employee>
<name>A</name>
<date-of-birth>01-02-80</date-of-birth>
<city>Delhi</city>
</employee>
<employee>
<name>B</name>
<date-of-birth>02-02-80</date-of-birth>
<city>Delhi</city>
</employee>
<employee>
<name>C</name>
<date-of-birth>03-02-80</date-of-birth>
<city>Delhi</city>
</employee>
<employee>
<name>D</name>
<date-of-birth>04-02-80</date-of-birth>
<city>Delhi</city>
</employee>
</roseindia>
2)ParseXML.java:
import org.w3c.dom.*;
import javax.xml.parsers.*;
public class ParseXML{
public static boolean isTextNode(Node n){
return n.getNodeName().equals("#text");
}
public static void main(String[]args)throws Exception{
DocumentBuilderFactory docFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("roseindia.xml");
Element element = doc.getDocumentElement();
NodeList personNodes = element.getChildNodes();
for (int i=0; i<personNodes.getLength(); i++){
Node emp = personNodes.item(i);
if (isTextNode(emp))
continue;
NodeList NameDOBCity = emp.getChildNodes();
for (int j=0; j<NameDOBCity.getLength(); j++ ){
Node node = NameDOBCity.item(j);
if ( isTextNode(node))
continue;
System.out.print(node.getFirstChild().getNodeValue()+"\t ");
}
System.out.println();
}
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.