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.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class test {
public static void main(String args[]){
DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance(); // 建立 解析器工廠對象
try {
DocumentBuilder db=dbf.newDocumentBuilder(); // 有工廠對象產生 解析器對象
Document doc =db.parse("D:\\Java\\Test\\src\\epet.xml"); //這就是 區別 呀 、 、 、
NodeList nlist=doc.getElementsByTagName("dog"); //擷取指定的節點集合、 、
System.out.println("xml中共有 "+nlist.getLength()+"條狗 的資訊"); // 列印 個數 。 、
for (int i = 0; i < nlist.getLength(); i++) {
Node dog=nlist.item(i);
Element s=(Element) dog;
String Attribute=s.getAttribute("id");
System.out.println("id:"+Attribute);
for (Node node = dog.getFirstChild(); node !=null; node=node.getNextSibling()) {
if(node.getNodeType()== Node.ELEMENT_NODE){
String name=node.getNodeName();
String value=node.getFirstChild().getNodeValue();
System.out.print(name+":"+value+"\t");
}
}
System.out.println();
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}