<?xml version="1.0" encoding="UTF-8" standalone="no"?> <contacts> <tr> <td>4</td> <td>广州市鼎和机械设备有限公司44</td> <td>东莞市寮步镇石大路147号</td> <td>公海客户</td> <td>线下广告</td> <td>2022-05-10</td> </tr> <tr> <td>5</td> <td>广州市鼎和机械设备有限公司5555</td> <td>东莞市寮步镇石大路147号</td> <td>公海客户</td> <td>线下广告</td> <td>2022-05-10</td> </tr> <tr> <td>6</td> <td>广州市鼎和机械设备有限公司6666</td> <td>东莞市寮步镇石大路147号</td> <td>公海客户</td> <td>线下广告</td> <td>2022-05-10</td> </tr> </contacts>
package com.swift.xml; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class APP5 { public static void main(String[] args) throws Exception { File f = new File("e:/contacts.xml"); if(!f.exists()) return; System.out.println("xml存在"); InputStream in=new FileInputStream(f); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document document=factory.newDocumentBuilder().parse(in); Element root = document.getDocumentElement();//根节点 NodeList nodeList = root.getElementsByTagName("tr"); int length = nodeList.getLength(); for(int i=0;i<length;i++) { Element oTr =(Element)nodeList.item(i);//得到<tr> NodeList tdList = oTr.getElementsByTagName("td"); Element companyNameElel =(Element)tdList.item(1); String companyName = companyNameElel.getTextContent(); System.out.println(companyName); } in.close(); } }
标签:xml,w3c,JAVA,java,Element,io,import,解析 From: https://www.cnblogs.com/hua900822/p/17148978.html