Java XML 字符串解析为对象

标签 java xml dom xml-parsing

我试图将 XML 字符串从服务器传递到解析器并创建对象数组列表,但我当前得到的只是一个空数组列表。

获取和解析 XML 的代码

package parkinglot_api;

import java.net.*;
import java.sql.Date; 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.io.*;

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.InputSource;
import org.xml.sax.SAXException;

public class ParkingLotInstance {
/*
 * Parking Lot API instance
 *      Constructor
 *          URL - String
 *      getParkingLotInfo()
 *          Returns XML from Specified Server
 *      parseParkingLotInfo()
 *          XML - String
 *          Returns ArrayList of Lot Objects
 */

public static URL serverURL;

public ParkingLotInstance( URL connurl ){
    serverURL = connurl;
}

public String getParkingLotInfo(){
    //Get a response from API server

    URL APIurl = this.serverURL;
    String APIresponse = "";

    System.out.println(APIurl);
    try {
        APIurl.openConnection();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(APIurl.openStream()));

        String output;
        while ((output = in.readLine()) != null)
            APIresponse += output;
        in.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return APIresponse;

}

public ArrayList parseParkingLotInfo( String XML ){
        ArrayList lots = new ArrayList();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {

            //Using factory get an instance of document builder

             dbf.setNamespaceAware(false);
             DocumentBuilder builder = dbf.newDocumentBuilder();

             InputSource inStream = new InputSource();

             inStream.setCharacterStream(new StringReader(XML));
             Document dom = builder.parse(inStream);


            //get the root element
            Element docEle = dom.getDocumentElement();

            //get a nodelist of elements
            NodeList nl = docEle.getElementsByTagName("Lot");

            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
                    Lot l = parseLot(el);

                    //add it to list
                    lots.add(l);
                }
            }


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


        return lots;
}

public Lot parseLot(Element el){

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");

    //Initialize Parking Lot Variables
    int id = getIntValue(el,"id");
    int occupancy = getIntValue(el,"occupancy");
    Boolean status = Boolean.parseBoolean(getTextValue(el,"status"));
    String name = getTextValue(el,"name");
    Date updated = null;
    try {
        updated = (Date) dateFormat.parse(getTextValue(el,"updated"));
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    String description = getTextValue(el,"description");

    //Construct Parking Lot
    Lot lot = new Lot( 
         id
       , occupancy 
       , status
       , name
       , updated
       , description 
      );

    return lot;
}

/**
 * I take a xml element and the tag name, look for the tag and get
 * the text content
 * i.e for <employee><name>John</name></employee> xml snippet if
 * the Element points to employee node and tagName is 'name' I will return John
 */
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;
}


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

对象类

 package parkinglot_api;

 import java.util.Date;
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
 import com.thoughtworks.xstream.XStream;
 import com.thoughtworks.xstream.io.xml.DomDriver;

 public class Lot {
/*
 * Parking Lot Object
 *     ID: Unique Identifier
 *     Occupancy: The Current Amount of Cars in the Lot
 *     Status: Describes if the Lot is Open or Closed
 *     Name: A String Identifier of the Lot
 *     Updated: The Last time the Lot's current status record was updated.
 */

//Initiate Parking Lot Fields
public int id;
public int occupancy;
public Boolean status;
public String description;
public String name;
public Date updated;

//Parking Lot Constructor
public Lot( 
      int newId
    , int newOccupancy 
    , Boolean newStatus
    , String newName
    , Date newUpdated
    , String newDescription 
){

    id = newId;
    occupancy = newOccupancy;
    status = newStatus;
    name = newName;
    updated = newUpdated;
    description = newDescription;
}

//Convert Java Object to JSON
public String toJSON(){
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    String jsonLot = gson.toJson(this);
    return jsonLot;
}

//Convert Java Object to XML
public String toXML(){
    XStream xstream = new XStream(new DomDriver());
    xstream.alias("lot", Lot.class);
    String xml = xstream.toXML(this);

    return xml;
}
}

从实例类调用方法的类

 package parkinglot_api;

 import java.net.MalformedURLException;
 import java.net.URL;
 import java.util.ArrayList;


 public class Example {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    URL serverURL;
    try {
        serverURL = new URL("http://localhost:8080");

        ParkingLotInstance API = new ParkingLotInstance(serverURL);

        String parkingLotXML = API.getParkingLotInfo();

        ArrayList Lots = API.parseParkingLotInfo(parkingLotXML);

        System.out.println(Lots);

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

 }

XML

<?xml version='1.0' ?>
    <campus count='4'>
    <lot>
      <id>1</id>
      <occupancy>25</occupancy>
      <status>true</status>
      <description></description>
      <name>lot1</name>
      <updated class="sql-date">2012-10-05</updated>
    </lot>
    <lot>
      <id>2</id>
      <occupancy>25</occupancy>
      <status>true</status>
      <description></description>
      <name>lot2</name>
      <updated class="sql-date">2012-10-06</updated>
    </lot>
    <lot>
      <id>3</id>
      <occupancy>25</occupancy>
      <status>false</status>
      <description></description>
      <name>lot3</name>
      <updated class="sql-date">2012-10-07</updated>
    </lot>
    <lot>
      <id>4</id>
      <occupancy>25</occupancy>
      <status>true</status>
      <description></description>
      <name>lot4</name>
      <updated class="sql-date">2012-11-07</updated>
    </lot>
    </campus>

最佳答案

我认为最好的解决方案是使用 JAXB,它可以为您完成所有工作。 你可以找到一个很好的教程here

关于Java XML 字符串解析为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10506812/

相关文章:

java - 在 poi-4.0.1 中找不到符号变量 Cell.CELL_TYPE_STRING

java - 为什么当我尝试通过 Intent 传递 Interface 对象时,Parcelable 遇到 IOException

java - SQLite: "DATABASE"附近:语法错误

java - Actionbarsherlock 在 Android 4.x 中不会显示菜单项

javascript - 无法使用DOM获取背景颜色

java - 如何在 map 值是集合的情况下按值大小对 map 条目进行排序?

php - 谷歌地图 API 和 XML

c++ - 制作图形用户界面编辑器

javascript - 修改页面 DOM 的 Firefox 插件

javascript - 尝试更改元素的 DOM 属性,但在使用 document.body.innerHTML += 后更改被忽略。如果顺序交换,一切正常