aktuelle.kurse/oldies/m411/docs/Daten-Uebungen-CodeBeispiele/TestXml.java
Müller Harald 3fdacd20c0 muh
2022-07-28 09:14:44 +02:00

98 lines
2.3 KiB
Java

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class TestXml {
/**
* @param args
*/
public static void main(String[] args) {
String filename = "xml/characters.xml";
TestXml test = new TestXml();
NodeList list = test.generateNodeList(filename);
for (int i=0; i < list.getLength(); i++){
Node node = test.findSubNode("ARTIST", list.item(i));
//the text value in a node is considered to be a child
//so we have to get the childNode:
NodeList textList = node.getChildNodes();
System.out.println("Artist =" + textList.item(0).getNodeValue());
}
}
public NodeList generateNodeList(String filename){
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
Document doc = null;
try {
db = dbf.newDocumentBuilder();
doc = db.parse(new File(filename));
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//puts all text nodes into full-depth underneath this node:
doc.getDocumentElement().normalize();
//get list of CDs:
NodeList cdElements = doc.getElementsByTagName("CD");
return cdElements;
}
/**
* Finds sub-nodes in an existing node
* @param name name of child node we want
* @param node current node
* @return
*/
public Node findSubNode(String name, Node node) {
if (node.getNodeType() != Node.ELEMENT_NODE) {
System.err.println("Error: Search node not of element type");
System.exit(22);
}
if (! node.hasChildNodes()) return null;
NodeList list = node.getChildNodes();
for (int i=0; i < list.getLength(); i++) {
Node subnode = list.item(i);
if (subnode.getNodeType() == Node.ELEMENT_NODE) {
if (subnode.getNodeName().equals(name))
return subnode;
}
}
return null;
}
}