java 中读取XML文件

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class ReadXML {

public static void main(String[] args) {
List<String>list=new ArrayList<String>();
Map<String,List<String>>map=new HashMap<String,List<String>>();


try {
File file=new File("cfg/service-session.xml");

DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();

DocumentBuilder builder=factory.newDocumentBuilder();

Document document=builder.parse(file);

NodeList nl=document.getElementsByTagName("service-session");
// System.out.println(nl.getLength());

NodeList nl2=document.getElementsByTagName("sessionid");
// System.out.println(nl2.getLength());

for (int i = 0; i < nl.getLength(); i++) {
String serviceid=document.getElementsByTagName("serviceid")
.item(i).getFirstChild().getNodeValue();

System.out.println("serviceid:"+serviceid);

for (int j = 0; j < 1; j++) {
String targetCompID=document.getElementsByTagName("targetCompID")
.item(i).getFirstChild().getNodeValue();

System.out.println("targetCompID:"+targetCompID);

String targetSubId=document.getElementsByTagName("targetSubId")
.item(i).getFirstChild().getNodeValue();
System.out.println("targetSubId:"+targetSubId);
}
}

} catch (Exception e) {

e.printStackTrace();
}
}

}

原文地址:https://www.cnblogs.com/1a2b/p/8919185.html