import w c dom *
import javax xml parsers *
import java io *
public class Parse{
//Document可以看作是XML在内存中的一个镜像 那么一旦获取这个Document 就意味着可以通过对
//内存的操作来实现对XML的操作 首先第一步获取XML相关的Document
private Document doc=null
public void init(String xmlFile) throws Exception{
//很明显该类是一个单例 先获取产生DocumentBuilder工厂
//的工厂 在通过这个工厂产生一个DocumentBuilder
//DocumentBuilder就是用来产生Document的
DocumentBuilderFactory dbf=DocumentBuilderFactory newInstance()
DocumentBuilder db=dbf newDocumentBuilder()
//这个Document就是一个XML文件在内存中的镜像
doc=db parse(new File(xmlFile))
}
//该方法负责把XML文件的内容显示出来
public void viewXML(String xmlFile) throws Exception{
this init(xmlFile)
//在xml文件里 只有一个根元素 先把根元素拿出来看看
Element element=doc getDocumentElement()
System out println( 根元素为: +element getTagName())
NodeList nodeList=doc getElementsByTagName( dbstore )
System out println( dbstore节点链的长度: +nodeList getLength())
Node fatherNode=em( )
System out println( 父节点为: +fatherNode getNodeName())
//把父节点的属性拿出来
NamedNodeMap attributes=fatherNode getAttributes()
for(int i= i<attributes getLength()i++){
Node attribute=em(i)
System out println( dbstore的属性名为: +attribute getNodeName()+ 相对应的属性值为: +attribute getNodeValue())
}
NodeList childNodes = fatherNode getChildNodes()
System out println(childNodes getLength())
for(int j= j<childNodes getLength()j++){
Node childNode=em(j)
//如果这个节点属于Element 再进行取值
if(childNode instanceof Element){
//System out println( 子节点名为: +childNode getNodeName()+ 相对应的值为 +childNode getFirstChild() getNodeValue())
System out println( 子节点名为: +childNode getNodeName()+ 相对应的值为 +childNode getFirstChild() getNodeValue())
}
}
}
public static void main(String[] args)throws Exception{
Parse parse=new Parse()
//我的XML文件
parse viewXML( netct xml )
}
lishixinzhi/Article/program/Java/hx/201311/26710
java读取xml节点元素,主要使用java提供的解析xml的工具类SAXParserFactory,如下代码:
package xml.xmlreaderimport java.io.File
import java.net.URL
import java.util.Properties
import javax.xml.parsers.SAXParser
import javax.xml.parsers.SAXParserFactory
public class CFGParser {//解析xml文件的工具类
private Properties props
public Properties getProps() {
return props
}
public void setProps(Properties props) {
this.props = props
}
public void parse(String filename) throws Exception
{
CFGHandler handler = new CFGHandler()
SAXParserFactory factory = SAXParserFactory.newInstance()
factory.setNamespaceAware(false)
factory.setValidating(false)
SAXParser parser = factory.newSAXParser()
URL confURL = super.getClass().getClassLoader().getResource(filename)
if (confURL == null) {
System.out.println("Can't find configration file.")
return
}
try
{
parser.parse(confURL.toString(), handler)
this.props = handler.getProps()
}
finally {
factory = null
parser = null
handler = null
}
}
public void parseFile(String filename)
throws Exception
{
CFGHandler handler = new CFGHandler()
SAXParserFactory factory = SAXParserFactory.newInstance()
factory.setNamespaceAware(false)
factory.setValidating(false)
SAXParser parser = factory.newSAXParser()
File f = new File(filename)
if ((f == null) || (!f.exists()))
return
try
{
parser.parse(f, handler)
this.props = handler.getProps()
}
finally {
factory = null
parser = null
handler = null
}
}
}
package xml.xmlreader
import java.util.Properties
import org.xml.sax.Attributes
import org.xml.sax.SAXException
import org.xml.sax.helpers.DefaultHandler
public class CFGHandler extends DefaultHandler
{
private Properties props
private String currentSet
private String currentName
private StringBuffer currentValue = new StringBuffer()
public CFGHandler()
{
this.props = new Properties()
}
public Properties getProps() {
return this.props
}
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException
{
this.currentValue.delete(0, this.currentValue.length())
this.currentName = qName
}
public void characters(char[] ch, int start, int length) throws SAXException
{
this.currentValue.append(ch, start, length)
}
public void endElement(String uri, String localName, String qName)
throws SAXException
{
this.props.put(qName.toLowerCase(), this.currentValue.toString().trim())
}
}
xml文件
<?xml version="1.0" encoding="UTF-8"?>
<xml-body>
<refresh_userlist desc="用户列表刷新间隔时间(秒)">6</refresh_userlist>
<refresh_message desc="短消息刷新间隔时间(秒)">10</refresh_message>
<morningbegin desc="上午上班时间">23:00</morningbegin>
<morningend desc="上午下班时间">12:00</morningend>
<afternoonbegin desc="下午上班时间">18:00</afternoonbegin>
</xml-body>
jsp获取各个节点的值:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<jsp:useBean id="cfgp" scope="page" class="xml.xmlreader.CFGParser"></jsp:useBean>
<body>
<%
cfgp.parse("kaoqin.xml")
Properties pro = cfgp.getProps()
String stTime = pro.getProperty("morningbegin")
String edTime = pro.getProperty("morningend")
String afternoonbegin = pro.getProperty("afternoonbegin")
out.println(stTime+"\n"+edTime+"\n"+afternoonbegin)
System.out.println(stTime+"\n"+edTime+"\n"+afternoonbegin)
%>
</body>
</html>
/*** xml文件解析
* @author young
*
*/
import java.io.*
import javax.xml.parsers.DocumentBuilder
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 XmlExam {
public static void main(String args[]) {
Element element = null
// 可以使用绝对路劲
File f = new File("xml1.xml")
// documentBuilder为抽象不能直接实例化(将XML文件转换为DOM文件)
DocumentBuilder db = null
DocumentBuilderFactory dbf = null
try {
// 返回documentBuilderFactory对象
dbf = DocumentBuilderFactory.newInstance()
// 返回db对象用documentBuilderFatory对象获得返回documentBuildr对象
db = dbf.newDocumentBuilder()
// 得到一个DOM并返回给document对象
Document dt = db.parse(f)
// 得到一个elment根元素
element = dt.getDocumentElement()
// 获得根节点
System.out.println("根元素:" + element.getNodeName())
// 获得根元素下的子节点
NodeList childNodes = element.getChildNodes()
// 遍历这些子节点
for (int i = 0 i < childNodes.getLength() i++) {
// 获得每个对应位置i的结点
Node node1 = childNodes.item(i)
if ("txtbook".equals(node1.getNodeName())) {
System.out.println("\r\n找到一个子节点: "
+ node1.getNodeName() + ". ")
// 获得<txtbook>下的节点
NodeList nodeDetail = node1.getChildNodes()
// 遍历<txtbook>下的节点
for (int j = 0 j < nodeDetail.getLength() j++) {
// 获得<wuxialist>元素每一个节点
Node detail = nodeDetail.item(j)
if ("name".equals(detail.getNodeName())) // 输出code
System.out
.println("name= " + detail.getTextContent())
else if ("author".equals(detail.getNodeName())) // 输出pass
System.out
.println("author= " + detail.getTextContent())
}
}
}
} catch (Exception e) {
e.printStackTrace()
}
}
}
这就是用java来解析xml文件。 要在java代码中导入xml解析的jar包。
4个jar包为:commons-beanutils.jar
commons-collections.jar
commons-digester.jar
commons-logging.jar
dom4j-1.6.1.jar
输出结果为: