Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Java解析XML_Java_Php_Xml - Fatal编程技术网

用Java解析XML

用Java解析XML,java,php,xml,Java,Php,Xml,我制作了一个PHP脚本,用于解析XML文件。这不容易使用,我想用Java实现它 在第一个元素中有各种计数的wfs:member元素,我循环通过: foreach ($data->children("wfs", true)->member as $member) { } 使用Java很容易做到这一点: NodeList wfsMember = doc.getElementsByTagName("wfs:member"); for(int i = 0; i < wfsMember

我制作了一个PHP脚本,用于解析XML文件。这不容易使用,我想用Java实现它

在第一个元素中有各种计数的
wfs:member
元素,我循环通过:

foreach ($data->children("wfs", true)->member as $member) { }
使用Java很容易做到这一点:

NodeList wfsMember = doc.getElementsByTagName("wfs:member");
for(int i = 0; i < wfsMember.getLength(); i++) { }
然后我需要从名为
observerdProperty
的元素中获取属性。在PHP中,这很简单:

$member->
    children("omso", true)->PointTimeSeriesObservation->
    children("om", true)->observedProperty->
    attributes("xlink", true)->href
但是在Java中,我如何做到这一点?如果我想深入结构,是否需要使用
getElementsByTagName
并循环它们`

在PHP中,整个脚本如下所示

foreach ($data->children("wfs", true)->member as $member) {
    $dataType = $dataTypes[(string) $member->
                    children("omso", true)->PointTimeSeriesObservation->
                    children("om", true)->observedProperty->
                    attributes("xlink", true)->href];

    foreach ($member->
            children("omso", true)->PointTimeSeriesObservation->
            children("om", true)->result->
            children("wml2", true)->MeasurementTimeseries->
            children("wml2", true)->point as $point) {

        $time = $point->children("wml2", true)->MeasurementTVP->children("wml2", true)->time;
        $value = $point->children("wml2", true)->MeasurementTVP->children("wml2", true)->value;

        $data[$dataType][] = array($time, $value)
    }
}

在第二个
foreach
I循环观察元素,从中获取时间和值数据。然后我将它保存在一个数组中。如果我需要以我所描述的方式循环Java中的元素,那么这是很难实现的。我不认为是这样的,所以有人能建议我如何在Java中实现类似的东西吗?

我不建议您为XML解析实现自己的解析函数,因为已经有很多选项了。我的建议是DOM解析器。您可以在下面的链接中找到一些示例。(您也可以从其他可用选项中进行选择)

您可以使用以下命令:

eElement.getAttribute("id");

来源:

我同意已经发布的关于不自己实现解析函数的内容

但是,我建议使用JDOM或XOM,它们是外部库,而不是DOM/SAX/STAX解析器

相关讨论:


我的直觉是jdom是大多数java开发人员使用的。有些使用dom4j,有些使用xom,有些使用其他,但几乎没有人自己实现这些解析函数。

如果性能不是主要问题,最简单的方法可能是XPath。使用XPath,只需指定路径即可找到节点和属性

XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile(<xpath_expression>);
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
有关XPath的更多信息,请参阅这本书。

DOM解析器通过递归实现 使用
DOM
解析器,您可以很容易地陷入嵌套的
for
循环的混乱,正如您已经指出的那样。然而,
DOM
结构由
Node
表示,包含子节点集合,其形式为
NodeList
,其中每个元素又是
节点
——这成为递归的完美候选对象

示例XML 为了展示
DOM
解析器不考虑XML大小的能力,我举了一个托管示例XML

XML
包含伦敦每3小时的天气预报。这个
XML
非常适合读取相对较大的数据集,并通过子元素中的属性提取特定信息

在快照中,我们的目标是收集由箭头标记的
元素

代码 首先,我们创建一个自定义类来保存温度和云的值。我们还将重写这个自定义类的
toString()
,以便方便地打印记录

ForeCast.java

public class ForeCast {

    /**
     * Overridden toString() to conveniently print the results
     */
    @Override
    public String toString() {
        return "The minimum temperature is: " + getTemperature()
                + " and the weather overall: " + getClouds();
    }

    public String getTemperature() {
        return temperature;
    }

    public void setTemperature(String temperature) {
        this.temperature = temperature;
    }

    public String getClouds() {
        return clouds;
    }

    public void setClouds(String clouds) {
        this.clouds = clouds;
    }

    private String temperature;
    private String clouds;
}
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class CustomDomXmlParser {

    // List collection which is would hold all the data parsed through the XML
    // in the format defined by the custom type 'ForeCast'
    private static List<ForeCast> forecastList = new ArrayList<>();

    public static void main(String[] args) throws ParserConfigurationException,
            SAXException, IOException {
        // Read XML throuhg a URL (a FileInputStream can be used to pick up an
        // XML file from the file system)
        InputStream path = new URL(
                "http://api.openweathermap.org/data/2.5/forecast?q=London,us&mode=xml")
                .openStream();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(path);

        // Call to the recursive method with the parent node
        traverse(document.getDocumentElement());

        // Print the List values collected within the recursive method
        for (ForeCast forecastObj : forecastList)
            System.out.println(forecastObj);

    }

    /**
     * 
     * @param node
     */
    public static void traverse(Node node) {
        // Get the list of Child Nodes immediate to the current node
        NodeList list = node.getChildNodes();

        // Declare our local instance of forecast object
        ForeCast forecastObj = null;

        /**
         * Logical block
         */
        // As per the XML syntax our 2 fields temperature and clouds come
        // directly under the Node/Element time
        if (node.getNodeName().equals("time")
                && node.getNodeType() == Node.ELEMENT_NODE) {

            // Instantiate our custom forecast object
            forecastObj = new ForeCast();
            Element timeElement = (Element) node;

            // Get the temperature element by its tag name within the XML (0th
            // index known)
            Element tempElement = (Element) timeElement.getElementsByTagName(
                    "temperature").item(0);
            // Minimum temperature value is selectively picked (for proof of
            // concept)
            forecastObj.setTemperature(tempElement.getAttribute("min"));

            // Similarly get the clouds element
            Element cloudElement = (Element) timeElement.getElementsByTagName(
                    "clouds").item(0);
            forecastObj.setClouds(cloudElement.getAttribute("value"));
        }

        // Add our foreCastObj if initialized within this recursion, that is if
        // it traverses the time node within the XML, and not in any other case
        if (forecastObj != null)
            forecastList.add(forecastObj);

        /**
         * Recursion block
         */
        // Iterate over the next child nodes
        for (int i = 0; i < list.getLength(); i++) {
            Node currentNode = list.item(i);
            // Recursively invoke the method for the current node
            traverse(currentNode);

        }

    }
}
现在进入正课。在执行递归的主类中,我们希望创建一个
列表
,其中包含
预测
对象,这些对象通过遍历整个XML来存储各个温度和云记录

// List collection which is would hold all the data parsed through the XML
// in the format defined by the custom type 'ForeCast'
private static List<ForeCast> forecastList = new ArrayList<>();
此后,我们将获得温度和云元素的句柄,这些元素可以设置为
ForeCast
对象

    // Get the temperature element by its tag name within the XML (0th
    // index known)
    Element tempElement = (Element) timeElement.getElementsByTagName("temperature").item(0);
    // Minimum temperature value is selectively picked (for proof of concept)
    forecastObj.setTemperature(tempElement.getAttribute("min"));

    // Similarly get the clouds element
    Element cloudElement = (Element) timeElement.getElementsByTagName("clouds").item(0);
    forecastObj.setClouds(cloudElement.getAttribute("value"));
完整的课程如下:

CustomDomXmlParser.java

public class ForeCast {

    /**
     * Overridden toString() to conveniently print the results
     */
    @Override
    public String toString() {
        return "The minimum temperature is: " + getTemperature()
                + " and the weather overall: " + getClouds();
    }

    public String getTemperature() {
        return temperature;
    }

    public void setTemperature(String temperature) {
        this.temperature = temperature;
    }

    public String getClouds() {
        return clouds;
    }

    public void setClouds(String clouds) {
        this.clouds = clouds;
    }

    private String temperature;
    private String clouds;
}
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class CustomDomXmlParser {

    // List collection which is would hold all the data parsed through the XML
    // in the format defined by the custom type 'ForeCast'
    private static List<ForeCast> forecastList = new ArrayList<>();

    public static void main(String[] args) throws ParserConfigurationException,
            SAXException, IOException {
        // Read XML throuhg a URL (a FileInputStream can be used to pick up an
        // XML file from the file system)
        InputStream path = new URL(
                "http://api.openweathermap.org/data/2.5/forecast?q=London,us&mode=xml")
                .openStream();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(path);

        // Call to the recursive method with the parent node
        traverse(document.getDocumentElement());

        // Print the List values collected within the recursive method
        for (ForeCast forecastObj : forecastList)
            System.out.println(forecastObj);

    }

    /**
     * 
     * @param node
     */
    public static void traverse(Node node) {
        // Get the list of Child Nodes immediate to the current node
        NodeList list = node.getChildNodes();

        // Declare our local instance of forecast object
        ForeCast forecastObj = null;

        /**
         * Logical block
         */
        // As per the XML syntax our 2 fields temperature and clouds come
        // directly under the Node/Element time
        if (node.getNodeName().equals("time")
                && node.getNodeType() == Node.ELEMENT_NODE) {

            // Instantiate our custom forecast object
            forecastObj = new ForeCast();
            Element timeElement = (Element) node;

            // Get the temperature element by its tag name within the XML (0th
            // index known)
            Element tempElement = (Element) timeElement.getElementsByTagName(
                    "temperature").item(0);
            // Minimum temperature value is selectively picked (for proof of
            // concept)
            forecastObj.setTemperature(tempElement.getAttribute("min"));

            // Similarly get the clouds element
            Element cloudElement = (Element) timeElement.getElementsByTagName(
                    "clouds").item(0);
            forecastObj.setClouds(cloudElement.getAttribute("value"));
        }

        // Add our foreCastObj if initialized within this recursion, that is if
        // it traverses the time node within the XML, and not in any other case
        if (forecastObj != null)
            forecastList.add(forecastObj);

        /**
         * Recursion block
         */
        // Iterate over the next child nodes
        for (int i = 0; i < list.getLength(); i++) {
            Node currentNode = list.item(i);
            // Recursively invoke the method for the current node
            traverse(currentNode);

        }

    }
}
import java.io.IOException;
导入java.io.InputStream;
导入java.net.URL;
导入java.util.ArrayList;
导入java.util.List;
导入javax.xml.parsers.DocumentBuilder;
导入javax.xml.parsers.DocumentBuilderFactory;
导入javax.xml.parsers.parserConfiguration异常;
导入org.w3c.dom.Document;
导入org.w3c.dom.Element;
导入org.w3c.dom.Node;
导入org.w3c.dom.NodeList;
导入org.xml.sax.SAXException;
公共类CustomDomXmlParser{
//列表集合,它将保存通过XML解析的所有数据
//采用自定义类型“ForeCast”定义的格式
私有静态列表forecastList=newArrayList();
公共静态void main(字符串[]args)引发ParserConfiguration异常,
SAXException,IOException{
//通过URL读取XML(FileInputStream可用于获取
//XML文件(来自文件系统)
InputStream路径=新URL(
"http://api.openweathermap.org/data/2.5/forecast?q=London,us&mode=xml)
.openStream();
DocumentBuilderFactory工厂=DocumentBuilderFactory.newInstance();
DocumentBuilder=factory.newDocumentBuilder();
Document=builder.parse(路径);
//使用父节点调用递归方法
遍历(document.getDocumentElement());
//打印递归方法中收集的列表值
for(ForeCast ForecastBJ:forecastList)
系统输出打印LN(forecastObj);
}
/**
* 
*@param节点
*/
公共静态空心导线测量(节点){
//获取与当前节点相邻的子节点列表
NodeList list=node.getChildNodes();
//声明预测对象的本地实例
ForeCast ForecastBj=null;
/**
*逻辑块
*/
//根据XML语法,我们的两个字段是温度和云
//直接在节点/元素时间下
if(node.getNodeName().equals(“时间”)
&&node.getNodeType()==node.ELEMENT\u node){
//实例化我们的自定义预测对象
ForecastBj=新预测();
元素timeElement=(元素)节点;
//通过XML中的标记名获取温度元素(第0个
//索引(已知)
Element tempElement=(Element)timeElement.getElementsByTagName(
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class CustomDomXmlParser {

    // List collection which is would hold all the data parsed through the XML
    // in the format defined by the custom type 'ForeCast'
    private static List<ForeCast> forecastList = new ArrayList<>();

    public static void main(String[] args) throws ParserConfigurationException,
            SAXException, IOException {
        // Read XML throuhg a URL (a FileInputStream can be used to pick up an
        // XML file from the file system)
        InputStream path = new URL(
                "http://api.openweathermap.org/data/2.5/forecast?q=London,us&mode=xml")
                .openStream();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(path);

        // Call to the recursive method with the parent node
        traverse(document.getDocumentElement());

        // Print the List values collected within the recursive method
        for (ForeCast forecastObj : forecastList)
            System.out.println(forecastObj);

    }

    /**
     * 
     * @param node
     */
    public static void traverse(Node node) {
        // Get the list of Child Nodes immediate to the current node
        NodeList list = node.getChildNodes();

        // Declare our local instance of forecast object
        ForeCast forecastObj = null;

        /**
         * Logical block
         */
        // As per the XML syntax our 2 fields temperature and clouds come
        // directly under the Node/Element time
        if (node.getNodeName().equals("time")
                && node.getNodeType() == Node.ELEMENT_NODE) {

            // Instantiate our custom forecast object
            forecastObj = new ForeCast();
            Element timeElement = (Element) node;

            // Get the temperature element by its tag name within the XML (0th
            // index known)
            Element tempElement = (Element) timeElement.getElementsByTagName(
                    "temperature").item(0);
            // Minimum temperature value is selectively picked (for proof of
            // concept)
            forecastObj.setTemperature(tempElement.getAttribute("min"));

            // Similarly get the clouds element
            Element cloudElement = (Element) timeElement.getElementsByTagName(
                    "clouds").item(0);
            forecastObj.setClouds(cloudElement.getAttribute("value"));
        }

        // Add our foreCastObj if initialized within this recursion, that is if
        // it traverses the time node within the XML, and not in any other case
        if (forecastObj != null)
            forecastList.add(forecastObj);

        /**
         * Recursion block
         */
        // Iterate over the next child nodes
        for (int i = 0; i < list.getLength(); i++) {
            Node currentNode = list.item(i);
            // Recursively invoke the method for the current node
            traverse(currentNode);

        }

    }
}
<?xml version="1.0" encoding="UTF-8"?>
<staff xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="oldEmployee.xsd">
    <employee>
        <name>Carl Cracker</name>
        <salary>75000</salary>
        <hiredate year="1987" month="12" day="15" />
    </employee>
    <employee>
        <name>Harry Hacker</name>
        <salary>50000</salary>
        <hiredate year="1989" month="10" day="1" />
    </employee>
    <employee>
        <name>Tony Tester</name>
        <salary>40000</salary>
        <hiredate year="1990" month="3" day="15" />
    </employee>
</staff>
class DomXmlParser {    
    private Document document;
    List<Employee> empList = new ArrayList<>();

    public SchemaFactory schemaFactory;
    public final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
    public final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";    

    public DomXmlParser() {  
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
            DocumentBuilder builder = factory.newDocumentBuilder();
            document = builder.parse(new File(EMPLOYEE_XML.getFilename()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }    

    public List<Employee> parseFromXmlToEmployee() {
        NodeList nodeList = document.getDocumentElement().getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);

            if (node instanceof Element) {
                Employee emp = new Employee();

                NodeList childNodes = node.getChildNodes();
                for (int j = 0; j < childNodes.getLength(); j++) {
                    Node cNode = childNodes.item(j);

                    // identify the child tag of employees
                    if (cNode instanceof Element) {
                        switch (cNode.getNodeName()) {
                            case "name":
                                emp.setName(text(cNode));
                                break;
                            case "salary":
                                emp.setSalary(Double.parseDouble(text(cNode)));
                                break;
                            case "hiredate":
                                int yearAttr = Integer.parseInt(cNode.getAttributes().getNamedItem("year").getNodeValue());
                                int monthAttr =  Integer.parseInt(cNode.getAttributes().getNamedItem("month").getNodeValue());
                                int dayAttr =  Integer.parseInt(cNode.getAttributes().getNamedItem("day").getNodeValue());

                                emp.setHireDay(yearAttr, monthAttr - 1, dayAttr);
                                break;
                        }
                    }
                }
                empList.add(emp);
            }
        }
        return empList;
    }
    private String text(Node cNode) {
        return cNode.getTextContent().trim();
    }
}
class SaxHandler extends DefaultHandler {

    private Stack<String> elementStack = new Stack<>();
    private Stack<Object> objectStack = new Stack<>();

    public List<Employee> employees = new ArrayList<>();
    Employee employee = null;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        this.elementStack.push(qName);

        if ("employee".equals(qName)) {
            employee = new Employee();
            this.objectStack.push(employee);
            this.employees.add(employee);
        }
        if("hiredate".equals(qName))
        {
            int yearatt = Integer.parseInt(attributes.getValue("year"));
            int monthatt = Integer.parseInt(attributes.getValue("month"));
            int dayatt = Integer.parseInt(attributes.getValue("day"));

            if (employee != null) {
                employee.setHireDay(yearatt,  monthatt - 1,  dayatt) ;
            }
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        this.elementStack.pop();

        if ("employee".equals(qName)) {
            Object objects = this.objectStack.pop();
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String value = new String(ch, start, length).trim();
        if (value.length() == 0) return;        // skip white space

        if ("name".equals(currentElement())) {
            employee = (Employee) this.objectStack.peek();
            employee.setName(value);
        } else if ("salary".equals(currentElement()) && "employee".equals(currentParrentElement())) {
            employee.setSalary(Double.parseDouble(value));
        }
    }

    private String currentElement() {
        return this.elementStack.peek();
    }

    private String currentParrentElement() {
        if (this.elementStack.size() < 2) return null;
        return this.elementStack.get(this.elementStack.size() - 2);
    }
}
class StaxXmlParser {
    private List<Employee> employeeList;
    private Employee currentEmployee;
    private String tagContent;
    private String attrContent;
    private XMLStreamReader reader;
    public StaxXmlParser(String filename) {
        employeeList = null;
        currentEmployee = null;
        tagContent = null;

        try {
            XMLInputFactory factory = XMLInputFactory.newFactory();
            reader = factory.createXMLStreamReader(new FileInputStream(new File(filename)));
            parseEmployee();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<Employee> parseEmployee() throws XMLStreamException {
        while (reader.hasNext()) {
            int event = reader.next();
            switch (event) {
                case XMLStreamConstants.START_ELEMENT:
                    if ("employee".equals(reader.getLocalName())) {
                        currentEmployee = new Employee();
                    }
                    if ("staff".equals(reader.getLocalName())) {
                        employeeList = new ArrayList<>();
                    }
                    if ("hiredate".equals(reader.getLocalName())) {
                        int yearAttr = Integer.parseInt(reader.getAttributeValue(null, "year"));
                        int monthAttr = Integer.parseInt(reader.getAttributeValue(null, "month"));
                        int dayAttr = Integer.parseInt(reader.getAttributeValue(null, "day"));

                        currentEmployee.setHireDay(yearAttr, monthAttr - 1, dayAttr);
                    }
                    break;

                case XMLStreamConstants.CHARACTERS:
                    tagContent = reader.getText().trim();
                    break;

                case XMLStreamConstants.ATTRIBUTE:
                    int count = reader.getAttributeCount();
                    for (int i = 0; i < count; i++) {
                        System.out.printf("count is: %d%n", count);
                    }
                    break;

                case XMLStreamConstants.END_ELEMENT:
                    switch (reader.getLocalName()) {
                        case "employee":
                            employeeList.add(currentEmployee);
                            break;
                        case "name":
                            currentEmployee.setName(tagContent);
                            break;
                        case "salary":
                            currentEmployee.setSalary(Double.parseDouble(tagContent));
                            break;
                    }
            }
        }
        return employeeList;
    }    
}
 public static void main(String[] args) {
    long startTime, elapsedTime;
    Main main = new Main();

    startTime = System.currentTimeMillis();
    main.testSaxParser();   // test
    elapsedTime = System.currentTimeMillis() - startTime;
    System.out.println(String.format("Parsing time is: %d ms%n", elapsedTime / 1000));

    startTime = System.currentTimeMillis();
    main.testStaxParser();  // test
    elapsedTime = System.currentTimeMillis() - startTime;
    System.out.println(String.format("Parsing time is: %d ms%n", elapsedTime / 1000));

    startTime = System.currentTimeMillis();
    main.testDomParser();  // test
    elapsedTime = System.currentTimeMillis() - startTime;
    System.out.println(String.format("Parsing time is: %d ms%n", elapsedTime / 1000));
}
Using SAX Parser:
-----------------
Employee { name=Carl Cracker, salary=75000.0, hireDay=Tue Dec 15 00:00:00 EET 1987 }
Employee { name=Harry Hacker, salary=50000.0, hireDay=Sun Oct 01 00:00:00 EET 1989 }
Employee { name=Tony Tester, salary=40000.0, hireDay=Thu Mar 15 00:00:00 EET 1990 }
Parsing time is: 106 ms

Using StAX Parser:
------------------
Employee { name=Carl Cracker, salary=75000.0, hireDay=Tue Dec 15 00:00:00 EET 1987 }
Employee { name=Harry Hacker, salary=50000.0, hireDay=Sun Oct 01 00:00:00 EET 1989 }
Employee { name=Tony Tester, salary=40000.0, hireDay=Thu Mar 15 00:00:00 EET 1990 }
Parsing time is: 5 ms

Using DOM Parser:
-----------------
Employee { name=Carl Cracker, salary=75000.0, hireDay=Tue Dec 15 00:00:00 EET 1987 }
Employee { name=Harry Hacker, salary=50000.0, hireDay=Sun Oct 01 00:00:00 EET 1989 }
Employee { name=Tony Tester, salary=40000.0, hireDay=Thu Mar 15 00:00:00 EET 1990 }
Parsing time is: 13 ms
public class JaxbDemo {
    public static void main(String[] args) {
        try {
            long startTime = System.currentTimeMillis();
            // create jaxb and instantiate marshaller
            JAXBContext context = JAXBContext.newInstance(Staff.class.getPackage().getName());
            FileInputStream in = new FileInputStream(new File(Files.EMPLOYEE_XML.getFilename()));

            System.out.println("Output from employee XML file");
            Unmarshaller um = context.createUnmarshaller();
            Staff staff = (Staff) um.unmarshal(in);

            // print employee list
            for (Staff.Employee emp : staff.getEmployee()) {
                System.out.println(emp);
            }

            long elapsedTime = System.currentTimeMillis() - startTime;
            System.out.println(String.format("Parsing time is: %d ms%n", elapsedTime));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Employee { name='Carl Cracker', salary=75000, hiredate=1987-12-15 } }
Employee { name='Harry Hacker', salary=50000, hiredate=1989-10-1 } }
Employee { name='Tony Tester', salary=40000, hiredate=1990-3-15 } }
Parsing time is: 320 ms
List<XmlElement> elements = Xsylum.elementFor(xmlFile).getAll("wfs:member");
for (XmlElement e : elements)
  String dataType = e.get("omso").get("om").attribute("xlink");
List<String> values = Xsylum.documentFor(xmlFile).values("//omso/om/@href");