Source code for XMLPhoneEntries.java
package PhoneApp.XML;
import java.util.Stack;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.apache.xerces.parsers.DOMParser;
public class XMLPhoneEntries extends Stack {
public XMLPhoneEntries(String fileName) {
initialize(fileName);
}
private void initialize(String fileName) {
parser = new DOMParser();
try {
parser.parse(fileName);
Document phoneList = parser.getDocument();
processRoot(phoneList);
} catch ( Exception e ) {
System.out.println("Unable to parse " + fileName);
}
}
private void processRoot(Node node) {
if ( node == null ) {
return;
} else {
Node doc = ((Document)node).getDocumentElement();
NodeList children = doc.getChildNodes();
for(int i=0; i< children.getLength(); i++) {
Node item = children.item(i);
String elementName = "PhonebookEntry";
if ( elementName.equals(item.getNodeName())) {
parseEntries(children.item(i));
}
}
}
}
private void parseEntries(Node node) {
String[] container = new String[7];
if ( node == null ) {
return;
} else {
NodeList children = node.getChildNodes();
for(int i=0; i< children.getLength(); i++) {
int fieldNumber = i/2;
Node item = children.item(i);
if ( item.getNodeType() == Node.ELEMENT_NODE ) {
NodeList values = item.getChildNodes();
String nodeValue = "";
for(int j=0; j< values.getLength() ; j++) {
Node value = values.item(j);
nodeValue = value.getNodeValue();
}
container[fieldNumber] = nodeValue;
}
}
}
push(container);
}
private DOMParser parser;
}