Java,简单的XML解析列表

时间:2015-12-25 08:20:05

标签: java android xml xml-parsing simple-framework

如何用Java解析这个列表?我有从服务器返回的列表,但我无法获得单个项目。

<images>
   <image>
       uploads/posts/2008-10/1225141003_1-21.jpg
   </image>
    <image>
       uploads/posts/2008-10/1225141003_1-22.jpg
   </image>
</images>
  

@Root(name =“Images”)公共类图片{

@ElementList(required=false, inline = true)
private List<Image> imageList;

public List<Image> getImageList() {
    return imageList;
} 
     

}

     

@Root(name =“image”)public class Image {

     

//一些代码.......

     

}

4 个答案:

答案 0 :(得分:0)

试试这个:

String inputStreamToString(InputStream is) {
    String line = "";
    String total = "";
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

    try {
        while ((line = rd.readLine()) != null) {
            total +=line;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return total;
}

修改

如果你能得到那个xml:

String responseXML = inputStreamToString(yourXMLResponseFromServer.getEntity().getContent());

答案 1 :(得分:0)

为了解释XML文件,我一直使用w3c.org.dom.Document接口,它提供类似文档修改的Javascript。查看oracle网站上的Documentation

答案 2 :(得分:0)

圣诞快乐

使用DOM和Xpath

1解析您的字符串

String xml="<my_xml/>";
DocumentBuilderFactory builderFactory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));

2使用xpath

XPath xPath = XPathFactory.newInstance().newXPath();
String expression="/images/image";
XPathExpression expr = xpath.compile(expression) ; 
NodeList nodes  = (NodeList) expr.evaluate(document,  XPathConstants.NODESET);

3次迭代

for (int k = 0; k < nodes.getLength(); k++)
    {
    Node nodeSegment = nodes.item(k);
    if (nodeSegment.getNodeType() == Node.ELEMENT_NODE)
        {
        Element eElement = (Element) nodeSegment;
        System.out.println("TEXT CONTENT="+eElement.getTextContent());

<强> ALTERNATIVE:

如果你知道你有1或2张图片:

expression="/images/image[1]"; // first one
String value = xPath.evaluate(expression, document);
System.out.println("EVALUATE:"+value);

答案 3 :(得分:0)

我用这种方式解决了这个问题:

@Root(name = "images") 
public class Images {

     @ElementList(entry = "image", required=false, inline = true)
     private List<String> imageList;

     public List<String> getImageList() {
         return imageList;
     }
}