package dom;
/**
 * parse xml file
 * @author Administrator
 *
 */
import javax.xml.parsers.*;
import org.w3c.dom.*;public class ParseXMLByDom {

//get document object by parse file
public Document  getDocumentByFile()throws Exception{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
Document doc=db.parse("student.xml");
return doc;
}
//parse xml file
public void parseXMLFile(Document doc)throws Exception{
//获得student元素的ID属性值
getStudentAttrValue(doc);
//获得student 的ID=101的子元素文本的内容
//getChildEleText(doc);
}
public void getStudentAttrValue(Document doc){
NodeList nodeLst=doc.getElementsByTagName("student");
int len=nodeLst.getLength();
for(int i=0;i<len;i++){
if(nodeLst.item(i) instanceof Element){
Element eleStu=(Element)nodeLst.item(i);
Attr attr=eleStu.getAttributeNode("ID");
System.out.println("ID value is: "+attr.getValue());
if(attr.getValue().equalsIgnoreCase("101")){
getChildEleText(eleStu);
}
}
}

}
public void getChildEleText(Element ele){
NodeList childLst=ele.getChildNodes();
int len=childLst.getLength();
for(int j=0;j<len;j++){
if(childLst.item(j) instanceof Element){
Element childEle=(Element)hildLst.item(j);
String tagName=childEle.getTagName();
String text=childEle.getTextContent();
System.out.println("<"+tagName+">"+text+"</"+tagName+">");
}
}
}
/**
 * @param args
 */
public static void main(String[] args) {
ParseXMLByDom parseXML=new ParseXMLByDom();
try{
parseXML.getStudentAttrValue(parseXML.getDocumentByFile());
}catch(Exception ex){
ex.printStackTrace();
} }}
 为什么String text=childEle.getTextContent();报错呢??怎么解决啊??

解决方案 »

  1.   

    org.w3c.dom *      Element的父类Node有getTextContent()为什么我在这儿用会出错??谁知道原因啊!!!!
      

  2.   

    因为你调用的那个方法是jdk下的那个包里的类,而在web项目里却调用了J2EE里的xml-apis.jar下的org.w3c.dom。(实际上要调用的那个方法是在jdk下的rt.jar下的org.w3c.dom)。我也被这个问题困扰了很久,后来把jdk和J2EE在项目里的位置调整了下就好了,即让jdk在J2EE上面.
      

  3.   

    后来把jdk和J2EE在项目里的位置调整了下就好了,即让jdk在J2EE上面. 
    能不能具体讲下怎么调整!!
      

  4.   

    String   text=childEle.getFirstChild().getNodeValue();
    试试吧
      

  5.   


    现将J2EE remove,然后编译,再将j2ee加上就可以了
      

  6.   

    顶啊!楼上讲得好啊!我把我项目的libraries的"Order and Export"中的JRE与J2EE顺序换了一个问题解决