【问题标题】:Java, Simple XML parsing listJava,简单 XML 解析列表
【发布时间】:2016-03-31 09:30:04
【问题描述】:

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

<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") 公共类图片 {

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

}

【问题讨论】:

  • 你想把它解析成什么?
  • 请再看一遍

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


【解决方案1】:

我是这样解决这个问题的:

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

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

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

【讨论】:

    【解决方案2】:

    试试这个:

    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());
    

    【讨论】:

      【解决方案3】:

      圣诞快乐

      使用 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());
      

      替代方案:

      如果您知道自己有 1 或 2 张图片:

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 2017-12-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-07
          • 1970-01-01
          • 2012-12-16
          • 1970-01-01
          相关资源
          最近更新 更多