直接貼代碼
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); //建立documentBuilderDocument document = builder.parse(new java.io.FileInputStream(new File("out.xml")),"utf8"); //讀取xml文件XPath xpath = XPathFactory.newInstance().newXPath(); //創建xpathString exp = "/html/body/table"; //讀取文件目錄NodeList table = (NodeList) xpath.evaluate(exp, document, XPathConstants.NODESET); //創建nodelist,找到根目錄就可以遍歷了 exp = "tbody/tr/td/table/tbody/tr";NodeList trs = (NodeList) xpath.evaluate(exp, table.item(0), XPathConstants.NODESET);exp="td";NodeList tds = (NodeList)xpath.evaluate(exp,trs.item(2),XPathConstants.NODESET);exp="table/tbody/tr";NodeList table_trs=(NodeList)xpath.evaluate(exp,tds.item(1),XPathConstants.NODESET);System.out.println(table_trs.getLength());exp="td";NodeList table_trs_tds = (NodeList)xpath.evaluate(exp, table_trs.item(0),XPathConstants.NODESET);for(int i=0;i<table_trs_tds.getLength();i++){Node node = table_trs_tds.item(i);System.out.println(new String(node.getTextContent().getBytes(),"UTF-8"));System.out.println(node.getAttributes().getNamedItem("align").getNodeValue());}
首先建立DocumentBuilder以便建立Document,用builder讀取文件。創建xpth,找到目錄,讀取所需要的內容。