XML的可使用XStream的解析得到特定对象对象、XML、XStream

2023-09-04 05:31:59 作者:彼岸花谢、满地忧伤

我是新来的XML解析,想转换一个web服务的POJO列表生成的XML文件。因为我做了使用JSON一些工作,发现它很容易与工作。而在XML的情况下,有安静的相同的过程,但我不能找到通过层次遍历和深远的特定节点被解析到POJO的方式。我解释我的问题与例子。这里是响应XML格式

I'm new to XML parsing and want to convert XML file resulting from a web service to list of POJOs. as i have done some work with JSon and found it very easy to work with. while in the case of XML there is quiet same process but i cant find way of traversing through the Hierarchy and reaching a specific node to be parsed to POJO. As i explain my question with example . here is response in XML format

<hash>

<resp_status>1</resp_status>

<message>success</message>

<errors></errors>

<calendars>
    <calendar>
        <id>44</id>

        <name>Air Force</name>

        <expiry_date>2012-03-01</expiry_date>

        <thumbnail_url>http://www.countdownyourgame.com/uploads/44_thumbnail.png</thumbnail_url>
    </calendar>
    <calendar>
        <id>103</id>

        <name>Akron</name>

        <expiry_date>2012-02-01</expiry_date>

        <thumbnail_url>http://www.countdownyourgame.com/uploads/103_thumbnail.png</thumbnail_url>
    </calendar>
    <calendar>
        <id>16</id>

        <name>Alabama</name>

        <expiry_date>2012-03-01</expiry_date>

        <thumbnail_url>http://www.countdownyourgame.com/uploads/16_thumbnail.png</thumbnail_url>
    </calendar>
</calendars>

和JSON格式相同的反应

and same response in JSon format

{
 "hash":
    {
     "resp_status":"1",
     "message":"success",
     "errors":"",
     "calendars":
        {
         "calendar":[
                     {
                      "id":"44",
                      "name":"Air Force",
                      "expiry_date":"2012-03-01",
                      "thumbnail_url":"https://m.xsw88.com/allimgs/daicuo/20230904/7492.png"
                      },

                      {
                       "id":"103",
                       "name":"Akron",
                       "expiry_date":"2012-02-01",
                       "thumbnail_url":"https://m.xsw88.com/allimgs/daicuo/20230904/7493.png"
                       },

                       {
                        "id":"16",
                        "name":"Alabama",
                        "expiry_date":"2012-03-01",
                        "thumbnail_url":"https://m.xsw88.com/allimgs/daicuo/20230904/7494.png"
                        }
                       ]
         }
    }
}

下面是对POJO里面包含日历(文件名Calendar.java)个日历对象

here is POJO for calendar objects contained inside calendars (file name Calendar.java)

public class Calendar {

private String id, name, expiry_date, thumbnail_url;

Calendar() {
    id = new String("");
    name = new String("");
    expiry_date = new String("");
    thumbnail_url = new String("");
}

public String getId() {
    return id;

}

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

public String getName() {
    return name;

}

public void setName(String name) {
    this.name = name;
}

public String getExpiryDate() {
    return expiry_date;

}

public void setExpiryDate(String expiry_date) {
    this.expiry_date = expiry_date;
}

public String getThumbnailUrl() {
    return thumbnail_url;

}

public void setThumbnailUrl(String name) {
    this.thumbnail_url = name;
}

}

要转换成上述JSON响应我只需要以下code

to convert the above JSon response i just need following code

 JSONObject json=new JSONObject(JsonResponceString);
        for(int i=0;i<json.getJSONObject("hash").getJSONObject("calendars").getJSONArray("calendar").length();i++)
        {
            //by using refrenced jar of Gson
            Calendars obj=new Gson().fromJson(json.getJSONObject("hash").getJSONObject("calendars").getJSONArray("calendar").getJSONObject(i).toString(), Calendar.class);
            //ArrayList for calendar type objects
            calendarList.add(obj);

        }

与XML上述过程中,有很多解析器,但我发现XStream的简单之一。 这里所示的下面的链接的http://xstream.$c$chaus.org/tutorial。的HTML 的在实施例有一个对象不能阵列其换算为POJO如在code底部定义的对象的

for above process with XML there are many parsers but i found XStream the simple one. here as shown in the following link http://xstream.codehaus.org/tutorial.html in the example there is one object not array of objects which is converted to POJO as defined in bottom portion of code

这是我的问题,我怎么可以遍历抛出整个XML响应并获得特定的或所有日历对象(XML对象)可以在JSON被转换成字符串像,然后作为参数传递给 fromXML()方法,以便分析以POJO。

here is my question that how can i traverse throw whole XML response and get the specific or all calendar objects(XML objects) which can be converted to string like in JSon and then passed as an argument to fromXML() method so that parsed to POJO.

由我自己写一个类使用字符串的方法或定期EX pression将根据需要选择简单的解析时间相同数量的分割日历对象的任何想法,请帮助我,使一个干净的答案是,过程我想是可以或不可以,可能的,但不是这样......那么在哪些方面?

any idea of writing a class by my self to split calendar objects using string methods or regular expression will take the same amount of time as required to choose simple parsing so please help me by giving a clean answer that the process I'm trying is possible or not , possible but not this way...then in what way?

我也学习别人特别JAXB,但它需要的模式,虽然它甚至可以设计的POJO你,但如果我不需要整个XML进行解析与大多数解析器的我已经是他们很可能问题分析整个响应,因此,要求POJO的凌乱的结构这一点。如果我错了,那么请给我建议,但与一些实训... thankx

i also studied about others specially JAXB but it needs schema and although it can even design POJOs for you but what if i don't need the whole XML to be parsed the problem with most of parsers i have is they are likely to parse the whole response and hence demanding a messy structure of POJO for this. if I'm wrong then please suggest me but with some solid example...thankx

推荐答案

终于找到了类似的方式到JSON。我希望这可以帮助别人。 @parag这是我在问.........我AP preciate你的帮助,但是,这不是我一直在寻找的。

At last found the way resembling to JSon . i hope this can help someone else. @parag this is what i was asking.........i appreciate your help but that was not what i was looking for..

package com.samjanz.xmlparsing;

import java.util.ArrayList;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.samjanz.xmlparsing.helpers.MyConverter;
import com.samjanz.xmlparsing.helpers.MyHTTPConnector;
import com.samjanz.xmlparsing.pojos.Calendar;
import com.thoughtworks.xstream.XStream;

public class XmlParsingActivity extends Activity {

LinearLayout parent;
String serverResponce;
Document xmlDoc;
ArrayList<Calendar> calendarList;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    parent = (LinearLayout) findViewById(R.id.parent);
    XStream xstream = new XStream();
    xstream.alias("calendar", Calendar.class);

    calendarList = new ArrayList<Calendar>();
    String url = getText(R.string.calendar_url).toString();
    // get DOC
    xmlDoc = MyConverter.streamToDocument(MyHTTPConnector.UrlToStream(url));
    NodeList nodeLst = xmlDoc.getElementsByTagName("calendar");

    for (int i = 0; i < nodeLst.getLength(); i++) {
        Node node = nodeLst.item(i);
        if (node != null) {
            Calendar obj = (Calendar) xstream.fromXML(MyConverter
                    .nodeToString(node));
            calendarList.add(obj);
            LayoutParams lparams = new LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            TextView tv = new TextView(this);
            tv.setLayoutParams(lparams);
            tv.setText("\n\nLoop No:" + (i + 1) + "\nId = "
                    + calendarList.get(i).getId() + "\nName = "
                    + calendarList.get(i).getName() + "\nExpiry Date = "
                    + calendarList.get(i).getExpiryDate()
                    + "\nThumbnail Url = "
                    + calendarList.get(i).getThumbnailUrl());
            parent.addView(tv);

        }

    }
}

}