com.sun.org.apache.xerces.internal.dom.DeferredTextImpl cannot be cast to org.w3

public class DomXmlTest{
    public static void main(String[] args) {
		DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder db=dbf.newDocumentBuilder();
			Document doc=db.parse("test/url.xml");
			NodeList ol=doc.getElementsByTagName("helloworld");
			for(int i=0;i<ol.getLength();i++){
				Element e=(Element) ol.item(i);
				System.out.println(e.getAttribute("name"));
				NodeList ol1=e.getChildNodes();
				for(int k=0;k<ol1.getLength();k++){
                    //在xml文档节点前存在回车,制表符等都会占用一个节点Node,这一类Node是无法转为Element,会抛com.sun.org.apache.xerces.internal.dom.DeferredTextImpl cannot be cast to org.w3c.dom.Element。可在前加if判断节点类型
                        if(ol1.item(k).getNodeType()==Node.ELEMENT_NODE){
				Element e1=(Element) ol1.item(k);
				System.out.println(e1.getNodeName());
                            }
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}

你可能感兴趣的:(xml)