DOM解析XML文件步骤如下:
DocumentBuilderFactory--->DocumentBuilder-->Document 【builder.parse()】
import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class XMlReaderTest { /** * factory ------->build------------->doc--->nodelist------------->node------------->value * newInstance newDocumentBuilder parse getElementByTagName item,getFirstChild getNodeValue */ public static void main(String[] args) { //建立DocumentBuilderFactory ,以获取DocumentBuilder DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; Document doc = null; try { //建立DocumentBulider,以获取Document builder = factory.newDocumentBuilder(); doc=builder.parse("c:"+File.separator+"123.xml"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } NodeList nl = doc.getElementsByTagName("linkman"); for(int i=0 ;i<nl.getLength();i++){ Element e = (Element)nl.item(i); String name=e.getElementsByTagName("name").item(0).getFirstChild().getNodeValue(); String tel=e.getElementsByTagName("tel").item(0).getFirstChild().getNodeValue(); System.out.println("姓名:"+name+",电话号码:"+tel); } } }原文链接:https://www.f2er.com/xml/296084.html