使用XML文档Java中的属性创建类的实例

时间:2016-05-08 20:17:00

标签: java xml parsing

        import java.io.IOException;
        import java.util.Vector;

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

        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;

        import buildingInfo.Level;

        public class XmlParser {    

            public static void main(String[] args) {  
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                Vector<Level> vLvl = new Vector<Level>(30);
                try {
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document doc = builder.parse("C:\\Users\\BeatriceGhetel\\workspace\\IPProject\\src\\configuration\\Configure.xml");
                    NodeList itemList = doc.getElementsByTagName("LEVEL");

                    for (int i = 0; i < itemList.getLength(); i++) {
                        Node it = itemList.item(i);
                        if (it.getNodeType()==Node.ELEMENT_NODE) {
                            Element el = (Element) it;
                            NodeList L = el.getChildNodes();
                            for (int j=0; j< L.getLength(); j++) {

                                Node n = L.item(j);
                                if (n.getNodeType()==Node.ELEMENT_NODE) {                           
                                    buildingInfo.Level Lvl = new         BuildingInfo.Level();
                                    if (n.getNodeName().matches("HEIGHT")) {
                                        Lvl.Height = Float.parseFloat(n.getTextContent());
                                    }
                                    System.out.println(Lvl.Height + " inaltime nivel");
                                    Element e = (Element) n;                            
                                }
                            }
                        }
                    }
                } catch (Exception ex){
                    ex.printStackTrace();
                }
            }       
        }

    <BUILDING>
    <LEVEL>
        <LABEL> 0 </LABEL>
        <HEIGHT> 2.5 </HEIGHT>
        <WIDTH> 9 </WIDTH>
        <LENGHT> 8 </LENGHT>
        <CAPACITY> 120 </CAPACITY>
        <ROOM>
            <LABEL> 1 </LABEL>
            <TYPE> NORMALROOM </TYPE>
            <HEIGHT> 2.5 </HEIGHT>
            <WIDTH> 5 </WIDTH>
            <LENGTH> 5 </LENGTH>
            <CAPACITY> 40 </CAPACITY>
            <SPRINKLER> YES </SPRINKLER>
            <SMOKEDETECTOR> YES </SMOKEDETECTOR>
            <EXTINGUISHERNUMBER> 2 </EXTINGUISHERNUMBER>
            <DOORNUMBER> 1 </DOORNUMBER>
            <DOOR>
                <ID> 1 </ID>
                <TYPE > EXTERNAL </TYPE >
                <CAPACITY> 2 </CAPACITY>
                <POSITION> NORTH </POSITION>
            </DOOR>
        </ROOM>   

我尝试创建一个建筑模型,从配置的XML文档中获取属性。我遇到的问题是,我无法区分房间的高度或门的高度,也不能总是取高度,有时会采用长度而不是高度等其他值。我还需要弄清楚如何创建房间集合,以及为像门这样的嵌套项目创建对象。

2 个答案:

答案 0 :(得分:1)

我永远不会直接使用DOM Api。这个用例是例如commons-digester用于:https://commons.apache.org/proper/commons-digester/guide/core.html

此外,Dom4J是一种更加Java友好的处理DOM树的方法:http://dom4j.sourceforge.net/dom4j-1.6.1/guide.html,您可以在其中使用,例如嵌套元素的简单迭代器。

您使用的标准W3C DOM API旨在在Java,C ++和JavaScript IIRC之间使用通用API,因此您直接使用它非常复杂,正如您所注意到的那样。

答案 1 :(得分:1)

JAXB是解析XML对象的最简单方法之一。只是定义java类结构以匹配XML结构就可以发挥作用。它还以更简单的方式支持Collections(XML元素数组)。我已经开发了代码来解析给定的XML(Altered XML一点点来展示如何处理Level / Room / Door中的集合)。希望它会对你有所帮助。

XML文件 - Base.xml

<?xml version="1.0" encoding="UTF-8"?>
<BUILDING>
    <LEVEL>
        <LABEL>0</LABEL>
        <HEIGHT>2.5</HEIGHT>
        <WIDTH>9</WIDTH>
        <LENGHT>8</LENGHT>
        <CAPACITY>120</CAPACITY>
        <ROOM>
            <LABEL>1</LABEL>
            <TYPE>NORMALROOM</TYPE>
            <HEIGHT>2.5</HEIGHT>
            <WIDTH>5</WIDTH>
            <LENGTH>5</LENGTH>
            <CAPACITY>40</CAPACITY>
            <SPRINKLER>YES</SPRINKLER>
            <SMOKEDETECTOR>YES</SMOKEDETECTOR>
            <EXTINGUISHERNUMBER>2</EXTINGUISHERNUMBER>
            <DOORNUMBER>1</DOORNUMBER>
            <DOOR>
                <ID>1</ID>
                <TYPE>EXTERNAL</TYPE>
                <CAPACITY>2</CAPACITY>
                <POSITION>NORTH</POSITION>
            </DOOR>
            <DOOR>
                <ID>2</ID>
                <TYPE>EXTERNAL</TYPE>
                <CAPACITY>1</CAPACITY>
                <POSITION>SOUTH</POSITION>
            </DOOR>
        </ROOM>
        <ROOM>
            <LABEL>2</LABEL>
            <TYPE>DELUXEROOM</TYPE>
            <HEIGHT>2.5</HEIGHT>
            <WIDTH>5</WIDTH>
            <LENGTH>5</LENGTH>
            <CAPACITY>80</CAPACITY>
            <SPRINKLER>YES</SPRINKLER>
            <SMOKEDETECTOR>YES</SMOKEDETECTOR>
            <EXTINGUISHERNUMBER>2</EXTINGUISHERNUMBER>
            <DOORNUMBER>1</DOORNUMBER>
            <DOOR>
                <ID>3</ID>
                <TYPE>EXTERNAL</TYPE>
                <CAPACITY>2</CAPACITY>
                <POSITION>NORTH</POSITION>
            </DOOR>
            <DOOR>
                <ID>4</ID>
                <TYPE>EXTERNAL</TYPE>
                <CAPACITY>1</CAPACITY>
                <POSITION>SOUTH</POSITION>
            </DOOR>
        </ROOM>
    </LEVEL>
</BUILDING>

<强> Building.java

@XmlRootElement(name = "BUILDING")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({ Level.class })
public class Building {

    @XmlElement(name = "LEVEL")
    private Level levels[];

    public Level[] getLevels() {
        return levels;
    }

    public void setLevels(Level[] levels) {
        this.levels = levels;
    }

    @Override
    public String toString() {
        return "Building [levels=" + Arrays.toString(levels) + "]";
    }

}

<强> Door.java

@XmlRootElement(name = "DOOR")
@XmlAccessorType(XmlAccessType.FIELD)
public class Door {

    @XmlElement(name="ID")
    private String id;

    @XmlElement(name="TYPE")
    private String type;

    @XmlElement(name="CAPACITY")
    private String capacity;

    @XmlElement(name="POSITION")
    private String position;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getCapacity() {
        return capacity;
    }

    public void setCapacity(String capacity) {
        this.capacity = capacity;
    }

    public String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
    }


    @Override
    public String toString() {
        return "Door [id=" + id + ", type=" + type + ", capacity=" + capacity
                + ", position=" + position + "]";
    }
}

<强> Level.java

@XmlRootElement(name="LEVEL")
@XmlSeeAlso({Room.class})
@XmlAccessorType(XmlAccessType.FIELD)
public class Level {

    @XmlElement(name="LABEL")
    private String Label;

    @XmlElement(name="HEIGHT")
    private String Height;

    @XmlElement(name="ROOM")
    private Room rooms[];

    public Room[] getRoom() {
        return rooms;
    }

    public void setRoom(Room[] room) {
        this.rooms = room;
    }

    public String getLabel() {
        return Label;
    }

    public void setLabel(String label) {
        Label = label;
    }

    public String getHeight() {
        return Height;
    }

    public void setHeight(String height) {
        Height = height;
    }

    @Override
    public String toString() {
        return "Level [Label=" + Label + ", Height=" + Height + ", rooms="
                + Arrays.toString(rooms) + "]";
    }
}

<强> JAXBParser.java

public class JAXBParser {

    public static void main(String args[]) throws JAXBException{
        File file = new File("C:\\XMLParserDemo\\src\\Base.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Building.class);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        Building building = (Building) jaxbUnmarshaller.unmarshal(file);
        System.out.println(building);


    }

<强> Room.java

@XmlRootElement(name="ROOM")
@XmlSeeAlso({Door.class})
@XmlAccessorType(XmlAccessType.FIELD)
public class Room {

    @XmlElement(name="LABEL")
    private String label;

    @XmlElement(name="TYPE")
    private String type;    

    @XmlElement(name="HEIGHT")
    private String height;

    @XmlElement(name="WIDTH")
    private String width;

    @XmlElement(name="LENGTH")
    private String length;

    @XmlElement(name="CAPACITY")
    private String capacity;

    @XmlElement(name="SPRINKLER")
    private String sprinkler;

    @XmlElement(name="SMOKEDETECTOR")
    private String smokeDet;

    @XmlElement(name="EXTINGUISHERNUMBER")
    private String extNum;

    @XmlElement(name="DOORNUMBER")
    private String doorNumber;

    @XmlElement(name="DOOR")
    Door doors[];

    public Door[] getDoor() {
        return doors;
    }
    public void setDoor(Door[] door) {
        this.doors = door;
    }
    public String getHeight() {
        return height;
    }
    public void setHeight(String height) {
        this.height = height;
    }
    public String getWidth() {
        return width;
    }
    public void setWidth(String width) {
        this.width = width;
    }
    public String getLength() {
        return length;
    }
    public void setLength(String length) {
        this.length = length;
    }
    public String getCapacity() {
        return capacity;
    }
    public void setCapacity(String capacity) {
        this.capacity = capacity;
    }
    public String getSprinkler() {
        return sprinkler;
    }
    public void setSprinkler(String sprinkler) {
        this.sprinkler = sprinkler;
    }
    public String getSmokeDet() {
        return smokeDet;
    }
    public void setSmokeDet(String smokeDet) {
        this.smokeDet = smokeDet;
    }
    public String getExtNum() {
        return extNum;
    }
    public void setExtNum(String extNum) {
        this.extNum = extNum;
    }
    public String getDoorNumber() {
        return doorNumber;
    }
    public void setDoorNumber(String doorNumber) {
        this.doorNumber = doorNumber;
    }

    public String getLabel() {
        return label;
    }
    public void setLabel(String label) {
        this.label = label;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "Room [label=" + label + ", type=" + type + ", height=" + height
                + ", width=" + width + ", length=" + length + ", capacity="
                + capacity + ", sprinkler=" + sprinkler + ", smokeDet="
                + smokeDet + ", extNum=" + extNum + ", doorNumber="
                + doorNumber + ", doors=" + Arrays.toString(doors) + "]";
    }    

}