xml文件如下:
<?xml version="1.0" encoding="GB2312"?>
<学生花名册>
<学生 性别 = "男">
<姓名>gray</姓名>
<年龄>14</年龄>
<电话>1234567</电话>
</学生>
</学生花名册>
我想实现的是,判断根节点的内容是否为 “学生花名册”,如果是,才对整个xml文档进行解析,否则不进行解析。希望用w3c的那种解析方法实现,请教各位大神了~~
1 w3c dom解析
[code="java"] //DOM解析
//1 DocumentBuilder工厂
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//2 DocumentBuilder
DocumentBuilder db = dbf.newDocumentBuilder();
//3 解析
File f = new File("文件位置");
Document document = db.parse(f);
document.normalize();
document.normalizeDocument();
//4 取数据
Element rootElement = document.getDocumentElement();
if(!"学生花名册".equals(rootElement.getTagName())) {
System.out.println("退出");
}
//继续解析
[/code]
2、sax解析
[code="java"]
public class StudentHandler extends DefaultHandler {
private boolean canParse = true;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if("学生花名册".equals(qName)) {
canParse = false;
}
if(!canParse) {
System.out.println("退出");
return;
}
//继续解析
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if(!canParse) {
return;
}
//继续解析
}
//清理
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(!canParse) {
return;
}
//继续解析
}
}
[/code]
[code="java"]
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
File f = new File("文件位置");
StudentHandler u = new StudentHandler();
sp.parse(f, u);
[/code]
package FirstOne;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class TestStudent {
public static void main(String[] args) {
SAXReader r=new SAXReader();
try {
Document d=r.read(TestStudent.class.getClassLoader().getResource("xml/student.xml"));
Element e=d.getRootElement();
System.out.println(e.getName());
if(e.getName().equals("学生花名册")){
System.out.println("AAAAA");
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
打印结果:
学生花名册
AAAAA
呵呵 晚上寂寞 想再怎么操作 随便你
使用w3c加xpath,基于JDK,无需第三方jar包,功能强大。
[color=red]帮你写了个完整的例子,并且进行了封装:[/color]
[code="java"]import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class StudentXmlParseTest {
public static void main(String[] args) {
StudentXmlParseTest test = new StudentXmlParseTest();
String path = StudentXmlParseTest.class.getResource("students.xml")
.getPath();
List<Student> students = test.parseStudentsXml(path);
for (Student student : students) {
System.out.println(student);
}
}
/**
* 解析学生花名册
*/
public List<Student> parseStudentsXml(String path) {
XMLParseUtil xmlParse = null;
try {
xmlParse = new XMLParseUtil();
} catch (ParserConfigurationException e) {
throw new RuntimeException("创建XML解析器过程中有一个严重的配置错误!", e);
}
if (null != xmlParse) {
Document doc = null;
try {
doc = xmlParse.parseDocument(path);
} catch (MalformedURLException e) {
throw new RuntimeException("文件路径错误!找不到要解析的文件!", e);
} catch (SAXParseException e) {
throw new RuntimeException("文件格式错误!无法解析!", e);
} catch (IOException e) {
throw new RuntimeException("解析XML出错!", e);
} catch (SAXException e) {
throw new RuntimeException("解析XML出错!", e);
}
if (doc != null && doc.getDocumentElement() != null) {
String rootNodeName = doc.getDocumentElement().getTagName();
if ("学生花名册".equals(rootNodeName)) {
NodeList studentNodeList;
try {
studentNodeList = (NodeList) xmlParse.selectNodes(doc,
"//学生花名册/学生");
} catch (XPathExpressionException e) {
throw new RuntimeException("解析XML中的学生节点出错!", e);
}
List<Student> students = new ArrayList<Student>();
for (int i = 0; i < studentNodeList.getLength(); i++) {
Node studentNode = studentNodeList.item(i);
Student student = parseStudentNode(xmlParse,
studentNode);
students.add(student);
}
return students;
} else {
System.out.println("文件不是学生花名册:" + path);
}
}
}
return null;
}
/**
* 解析单个学生节点
*/
public Student parseStudentNode(XMLParseUtil util, Node node) {
String sex = getNodeStringValue(util, node, "./@性别");
String name = getNodeStringValue(util, node, "./姓名");
long age = getNodeLongValue(util, node, "./年龄");
long phone = getNodeLongValue(util, node, "./电话");
return new Student(sex, name, age, phone);
}
public static String getNodeStringValue(XMLParseUtil util, Node node,
String expression) {
try {
return util.getNodeStringValue(node, expression);
} catch (XPathExpressionException e) {
throw new RuntimeException("XPath表达式错误:" + expression, e);
}
}
public static long getNodeLongValue(XMLParseUtil util, Node node,
String expression) {
String value = getNodeStringValue(util, node, expression);
return Long.parseLong(value);
}
}[/code]
[color=red][b]解析的XML文件:【students.xml】[/b][/color]
[code="xml"]<?xml version="1.0" encoding="UTF-8"?>
<学生花名册>
<学生 性别="男">
<姓名>李冰</姓名>
<年龄>25</年龄>
<电话>159123123123</电话>
</学生>
</学生花名册>[/code]
[color=red][b]学生的Bean类:[/b][/color]
[code="java"]public class Student {
private String sex;
private String name;
private long age;
private long phone;
public Student(String sex, String name, long age, long phone) {
this.sex = sex;
this.name = name;
this.age = age;
this.phone = phone;
}
public String toString() {
return "学生 { 姓名:" + name + ", 性别:" + sex + ", 年龄:" + age + "电话:"
+ phone + "}";
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getAge() {
return age;
}
public void setAge(long age) {
this.age = age;
}
public long getPhone() {
return phone;
}
public void setPhone(long phone) {
this.phone = phone;
}
}[/code]
[color=red][b]解析XML的工具类:[/b][/color]
[code="java"]import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
@since [产品/模块版本]
*/
public class XMLParseUtil {
private DocumentBuilder builder;
private XPath xpath;
/**
创建XML解析器出错!
*/
public XMLParseUtil() throws ParserConfigurationException {
DocumentBuilderFactory domfactory = DocumentBuilderFactory
.newInstance();
builder = domfactory.newDocumentBuilder();
XPathFactory xpfactory = XPathFactory.newInstance();
xpath = xpfactory.newXPath();
}
/**
/**
/**
/**
/**
/**