为Java创建XML解析器

时间:2016-01-31 11:47:37

标签: java xml dom

我正在创建一个显示X3D模型的Java应用程序,并且我正在为它创建一个XML解析器。我拥有的Java代码是

package domparserexample.java;

import java.io.IOException;
import java.util.Iterator;
import javax.lang.model.element.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DomParserExampleJava {

    private void parseXmlFile() throws IOException,           ParserConfigurationException{
        //get the factory
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {

            //Using factory get an instance of document builder
            DocumentBuilder db = dbf.newDocumentBuilder();

                //parse using builder to get DOM representation of the XML file
                Document dom = db.parse("employees.xml");


        }catch(SAXException se) {
            se.printStackTrace();
        }catch(IOException ioe) {
            ioe.printStackTrace();
        }
    }

    private void parseDocument(){
        //get the root element
        Element docEle = dom.getDocumentElement();

        //get a nodelist of elements
        NodeList nl = docEle.getElementsByTagName("Employee");
        if(nl != null && nl.getLength() > 0) {
            for(int i = 0 ; i < nl.getLength();i++) {

                //get the employee element
                Element el = (Element)nl.item(i);

                //get the Employee object
                Employee e = getEmployee(el);

                //add it to list
                myEmpls.add(e);
            }
        }
    }
    /**
    * I take an employee element and read the values in, create
    * an Employee object and return it
    */
    private Employee getEmployee(Element empEl) {

        //for each <employee> element get text or int values of
        //name ,id, age and name
        String name = getTextValue(empEl,"Name");
        int id = getIntValue(empEl,"Id");
        int age = getIntValue(empEl,"Age");

        String type = empEl.getAttribute("type");

        //Create a new Employee with the value read from the xml nodes
        Employee e = new Employee(name,id,age,type);

        return e;
    }


    private String getTextValue(Element ele, String tagName) {
        String textVal = null;
        NodeList nl = ele.getElementsByTagName(tagName);
        if(nl != null && nl.getLength() > 0) {
            Element el = (Element)nl.item(0);
            textVal = el.getFirstChild().getNodeValue();
        }

        return textVal;
    }
    private int getIntValue(Element ele, String tagName) {
        //in production application you would catch the exception
        return Integer.parseInt(getTextValue(ele,tagName));
    }
    private void printData(){

        System.out.println("No of Employees '" + myEmpls.size() + "'.");

        Iterator it = myEmpls.iterator();
        while(it.hasNext()) {
            System.out.println(it.next().toString());
        }
    }
}

XML代码是:

<?xml version="1.0" encoding="UTF-8"?>
    <Personnel>
        <Employee type="permanent">
            <Name>Seagull</Name>
            <Id>3674</Id>
            <Age>34</Age>
        </Employee>
        <Employee type="contract">
            <Name>Robin</Name>
            <Id>3675</Id>
            <Age>25</Age>
        </Employee>
        <Employee type="permanent">
            <Name>Crow</Name>
            <Id>3676</Id>
            <Age>28</Age>
        </Employee>
    </Personnel>

但是,我在DomParserExample.java文件中的第49,76,93和96行出现了一些错误,我不知道它为什么会发生。所有错误均表示他们cannot find symbolsymbol: method getElemantsByTagName(String)symbol: method getAttribute(String)symbol: method getElementByTagName(String)symbol: method getFirstChild()

2 个答案:

答案 0 :(得分:0)

对我而言,它正在使用以下代码。我对你的代码做了一些修改。

<强> DomParserExampleJava.java

package domparserexample.java;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
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.NodeList;
import org.xml.sax.SAXException;

public class DomParserExampleJava {

    private List<Employee> myEmpls = new ArrayList<Employee>();

    public static void main(String[] args) throws IOException, ParserConfigurationException {
        DomParserExampleJava domParser = new DomParserExampleJava();
        domParser.parseXmlFile();
    }

    private void parseXmlFile() throws IOException, ParserConfigurationException {
        // get the factory
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {

            // Using factory get an instance of document builder
            DocumentBuilder db = dbf.newDocumentBuilder();

            // parse using builder to get DOM representation of the XML file
            Document dom = db.parse("employees.xml");
            parseDocument(dom);
            printData();

        } catch (SAXException se) {
            se.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    private void parseDocument(Document dom) {
        // get the root element
        Element docEle = dom.getDocumentElement();

        // get a nodelist of elements
        NodeList nl = docEle.getElementsByTagName("Employee");
        if (nl != null && nl.getLength() > 0) {
            for (int i = 0; i < nl.getLength(); i++) {

                // get the employee element
                Element el = (Element) nl.item(i);

                // get the Employee object
                Employee e = getEmployee(el);

                // add it to list
                myEmpls.add(e);
            }
        }
    }

    /**
     * I take an employee element and read the values in, create an Employee object and return it
     */
    private Employee getEmployee(Element empEl) {

        // for each <employee> element get text or int values of
        // name ,id, age and name
        String name = getTextValue(empEl, "Name");
        int id = getIntValue(empEl, "Id");
        int age = getIntValue(empEl, "Age");

        String type = empEl.getAttribute("type");

        // Create a new Employee with the value read from the xml nodes
        Employee e = new Employee(name, id, age, type);

        return e;
    }

    private String getTextValue(Element ele, String tagName) {
        String textVal = null;
        NodeList nl = ele.getElementsByTagName(tagName);
        if (nl != null && nl.getLength() > 0) {
            Element el = (Element) nl.item(0);
            textVal = el.getFirstChild().getNodeValue();
        }

        return textVal;
    }

    private int getIntValue(Element ele, String tagName) {
        // in production application you would catch the exception
        return Integer.parseInt(getTextValue(ele, tagName));
    }

    private void printData() {

        System.out.println("No of Employees '" + myEmpls.size() + "'.");

        Iterator<Employee> it = myEmpls.iterator();
        while (it.hasNext()) {
            System.out.println(it.next().toString());
        }
    }
}

<强> Employee.java

package domparserexample.java;

public class Employee {

    private String name;
    private int id;
    private int age;
    private String type;

    public Employee(String name, int id, int age, String type) {
        this.name = name;
        this.id = id;
        this.age = age;
        this.type = type;
    }

    public String toString() {
        return id + ": " + name + ", age: " + age + ", type: " + type;
    }

}

<强> employees.xml

在您的示例中,<?xml version="1.0" encoding="UTF-8"?>第二次出现在XML文档的中间。这会导致错误。

<?xml version="1.0" encoding="UTF-8"?>
<Personnel>
    <Employee type="permanent">
        <Name>Seagull</Name>
        <Id>3674</Id>
        <Age>34</Age>
    </Employee>
    <Employee type="contract">
        <Name>Robin</Name>
        <Id>3675</Id>
        <Age>25</Age>
    </Employee>
    <Employee type="permanent">
        <Name>Crow</Name>
        <Id>3676</Id>
        <Age>28</Age>
    </Employee>
</Personnel>

如果我执行Java文件,则返回:

No of Employees '3'.
3674: Seagull, age: 34, type: permanent
3675: Robin, age: 25, type: contract
3676: Crow, age: 28, type: permanent

答案 1 :(得分:0)

您使用的是错误的def method(option = {:flag => false}) flag = options.fetch(:flag) { false } unless [true, false].include?(flag) raise ArgumentError, ':flag option should be true or false' end flag? doFoo : doBar end method(:flag => true) 类:

ELement

错了,请使用:

import javax.lang.model.element.Element;

这应该有效。