繁体   English   中英

为Java创建XML解析器

[英]Creating a XML parser for Java

我正在制作一个显示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()

对我来说,它正在使用以下代码。 我对您的代码进行了一些更改。

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;
    }

}

员工.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

您使用了错误的ELement类:

import javax.lang.model.element.Element;

是错误的,使用:

import org.w3c.dom.Element;

那应该工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM