网上有xml解析包
package xml;
import java.util.*;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
import java.io.IOException;
import org.w3c.dom.Node;
import java.net.URL;
public classdo
MTest {
private void readXMLFile(String inFile) throws Exception {
// 为解析XML作准备,创建DocumentBuilderFactory实例,指定DocumentBuilder
do
cumentBuilderFactory dbf =do
cumentBuilderFactory.newInstance();
do
cumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException pce) {
System.err.println(pce);
System.exit(1);
}
do
cumentdo
c = null;
try {
do
c = db.parse(inFile);
} catch (DOMExceptiondo
m) {
System.err.println(dom.getMessage());
System.exit(1);
} catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
// 下面是解析XML的全过程,比较简单,先取根元素”学生花名册“
Element root =do
c.getDocumentElement();
// 取“学生“元素列表
NodeList students = root.getElementsByTagName("学生"
;
for (int i = 0;
i < students.getLength();
i++) {
// 依次取每个“学生”元素
Element student = (Element) students.item(i);
// 创建一个学生的Bean实例
// StudentBean studentBean = new StudentBean();
// 取学生的性别属性
// studentBean.setSex(student.getAttribute("性别"
);
// 取“姓名”元素,下同
NodeList names = student.getElementsByTagName("姓名"
;
if (names.getLength() == 1) {
Element e = (Element) names.item(0);
Text t = (Text) e.getFirstChild();
// studentBean.setName(t.getNodeValue());
}
NodeList ages = student.getElementsByTagName("年龄"
;
if (ages.getLength() == 1) {
Element e = (Element) ages.item(0);
Text t = (Text) e.getFirstChild();
// studentBean.setAge(Integer.parseInt(t.getNodeValue()));
}
NodeList phones = student.getElementsByTagName("电话"
;
if (phones.getLength() == 1) {
Element e = (Element) phones.item(0);
Text t = (Text) e.getFirstChild();
//studentBean.setPhone(t.getNodeValue());
}
// student_Vector.add(studentBean);
}
}
public static void testReadData(String fileName) {
String data;
DefaultParser parser = new DefaultParser();
try {
Document printFormatDoc = parser.parse(fileName);
NodeList formatTags = printFormatDoc
.getElementsByTagName("printdata"
;
for (int i = 0;
i < formatTags.getLength();
i++) {
Element ee = (Element) formatTags.item(i);
System.out.println(ee.getAttribute("pageno"
);;
NodeList variableTags = ee.getElementsByTagName("data"
;
if(variableTags.getLength()<1)
continue;
Element e = (Element) variableTags.item(0);
Text varNode = (Text) e.getFirstChild();
if (varNode != null) {
data = (String) varNode.getNodeValue();
System.out.println(data);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
testReadData("printdata.xml"
;
}
}