DOM解析XML,根节点标签内容判断

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;

/**

  • 解析XML的工具类,使用XPath
  • @author ChenFeng
  • @version [版本号, 2009-12-22]
  • @see [相关类/方法]
  • @since [产品/模块版本]
    */
    public class XMLParseUtil {
    private DocumentBuilder builder;

    private XPath xpath;

    /**

    • 默认构造函数
    • @throws ParserConfigurationException
    •         创建XML解析器出错!
      

      */
      public XMLParseUtil() throws ParserConfigurationException {
      DocumentBuilderFactory domfactory = DocumentBuilderFactory
      .newInstance();
      builder = domfactory.newDocumentBuilder();

      XPathFactory xpfactory = XPathFactory.newInstance();
      xpath = xpfactory.newXPath();
      }

    /**

    • 根据路径解析XML文档
    • 可能产生而没有显式抛出的异常:
    • 1) MalformedURLException :传入文件路径错误!找不到要解析的文件!
    • 2) SAXParseException : 文件格式错误!无法解析!
    • @param path
    • 文件路径
    • @return Document对象
    • @throws IOException
    • IO异常
    • @throws SAXException
    • SAX异常
    • @see [类、类#方法、类#成员] */ public Document parseDocument(String path) throws IOException, SAXException { return builder.parse(path); }

    /**

    • 根据文件解析XML文档
    • 可能产生而没有显式抛出的异常:
    • 1) IllegalArgumentException :传入参数错误!如对象不能为空!
    • 2) SAXParseException : 文件格式错误!无法解析!
    • @param file
    • 文件
    • @return Document对象
    • @throws IOException
    • IO异常
    • @throws SAXException
    • SAX异常
    • @see [类、类#方法、类#成员] */ public Document parseDocument(File file) throws IOException, SAXException { return builder.parse(file); }

    /**

    • 根据输入流解析XML文档
    • 可能产生而没有显式抛出的异常:
    • 1) IllegalArgumentException :传入参数错误!如对象不能为空!
    • 2) SAXParseException : 文件格式错误!无法解析!
    • @param is
    • 输入流
    • @return Document对象
    • @throws IOException
    • IO异常
    • @throws SAXException
    • SAX异常
    • @see [类、类#方法、类#成员] */ public Document parseDocument(InputStream is) throws IOException, SAXException { return builder.parse(is); }

    /**

    • 通过xpath取得节点列表
    • @param node
    • 节点
    • @param expression
    • XPath表达式
    • @return NodeList
    • @throws XPathExpressionException
    • XPath表达式异常
    • @see [类、类#方法、类#成员] */ public NodeList selectNodes(Node node, String expression) throws XPathExpressionException { // XPath对象编译XPath表达式 XPathExpression xpexpreesion = this.xpath.compile(expression); Object object = xpexpreesion.evaluate(node, XPathConstants.NODESET); return (NodeList) object; }

    /**

    • 通过xpath取得单个节点
    • @param node
    • 节点
    • @param expression
    • XPath表达式
    • @return Node
    • @throws XPathExpressionException
    • XPath表达式异常
    • @see [类、类#方法、类#成员] */ public Node selectSingleNode(Node node, String expression) throws XPathExpressionException { XPathExpression xpexpreesion = this.xpath.compile(expression); Object object = xpexpreesion.evaluate(node, XPathConstants.NODE); return (Node) object; }

    /**

    • 根据xpath取得节点的文本值
    • @param node
    • 节点
    • @param expression
    • XPath表达式
    • @return String
    • @throws XPathExpressionException
    • XPath表达式异常
    • @see [类、类#方法、类#成员] */ public String getNodeStringValue(Node node, String expression) throws XPathExpressionException { XPathExpression xpexpreesion = this.xpath.compile(expression); Object object = xpexpreesion.evaluate(node, XPathConstants.STRING); return (String) object; } }[/code]