【问题标题】:Simple Xml Parsing error in AndroidAndroid中的简单Xml解析错误
【发布时间】:2012-09-18 23:03:11
【问题描述】:
<GetProductsForMachine>
<Products>
    <ProductsForMachine>coffee espresso</ProductsForMachine>
    <ProductsForMachine>coffe1</ProductsForMachine>
    <ProductsForMachine>coffee2</ProductsForMachine>

</Products>

ProductsForMachine 类的实现必须是什么,很难,因为没有元素可以获取它们的值。

我尝试使用以下代码,但解析时出现错误..

@Root
public class ProductsForMachine{

    @Attribute(name="ProductsForMachine", required=true)
    public String ProductsForMachine;



    @Element(required=false)
    public int value;
}

谢谢

【问题讨论】:

  • it's difficult because there aren't elements to get theirs value. 为什么? ProductsForMachine在您的 XML 文件中有值。还是我误会了你?
  • 好的,请告诉我解析它的类必须是什么,因为我写的类在解析中不起作用..

标签: android xml-parsing simple-framework


【解决方案1】:

这是一个简单的解决方案,假设每个 <ProductsForMachine>...</ProductsForMachine> 条目都可以用字符串表示。

@Root(name="GetProductsForMachine")
public class GetProductsForMachine
{
    @ElementList(name="Products", entry="ProductsForMachine")
    private ArrayList<String> products; /* 1 */


    // Construtors / Methods

}

注意1:为什么使用ArrayList&lt;String&gt;而不是List&lt;String&gt;请参见here

由于设置了注释的name 值,因此可以重命名类/字段。

您现在可以像这样反序列化您的 XML:

File f = // your xml file

Serializer ser = new Persister();
GetProductsForMachine products = ser.read(GetProductsForMachine.class, f);

顺便说一句。 GetProductsForMachine 需要一个结束标签。

【讨论】:

    【解决方案2】:

    看看我对this question 的回答。它提供了一种在查找特定标签时解析简单 xml 的通用方法。

    【讨论】:

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