用jdk的dom解析xml例子 .

import java.io.FileInputStream;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Test2 {
 // Document 容器
 static Document doc = null;
 
 public static void main(String[] args) throws Exception
 {
  //加载XML文件:文件放在根目录下
  InputStream is = new FileInputStream("config.xml");
  doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
  // 获得 节点 ipname2的值
  String s = getParaValue("context-param");
  System.out.print(s.trim());
 }

/**
  * XML文档的解析
  */
 public static String getParaValue(String paraname) throws Exception {
  String returns = "";
  // 按文档顺序返回包含在文档中且具有给定标记名称的所有Element的NodeList
  NodeList nl = doc.getElementsByTagName(paraname);
  // 返回NodeList中的某一个节点
  Node n = nl.item(0);
  // 获取节点的值
  returns = n.getFirstChild().getNodeValue();
  return returns;
 }

}

config.xml文件

<?xml version="1.0" encoding="UTF-8"?>

<context-param>
 <ipname1>参数A</ipname1>
 <ipname2>参数B</ipname2>
</context-param>

原文地址:https://www.cnblogs.com/qqzy168/p/3136180.html