student0495 student0495 - 6 months ago 9
Java Question

Create instance of class with attributes from XML document Java

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>


I try to create a model of a building getting attributes from a XML document of configuration. The problem I have is that I cannot make a difference between the height of a room or height of a door, and it also doesn't always take the height, it sometimes take other values like length instead of height. I also need to figure out how to create a collection of rooms, and to create objects for the nested items like Doors.

Answer

JAXB is the one of the simplest way to parse XML objects. Just defining the java class structure to match the XML structure will do the magic. It also supports Collections(Array of XML elements) in a much simpler way. I have developed the code to the parse the given XML(Altered XML little bit to show how collections in Level/Room/Door can also be handled). Hope it will help you.

XML File - 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) + "]";
    }    

}
Comments