2016-08-01 29 views
2

我必须解析XML文件中的元素,可以是两种类型:的SimpleXML:用元素列表或文本

<property> 
    <value>Some text</value> 
</property> 

<property> 
    <value> 
     <item id="first_id"/> 
     <item id="second_id"/> 
     <item id="third_id"/> 
    </value> 
</property> 

我怎样才能做到这一点与Java?

我创建了一个类:

@Root(strict = false) 
public class PropertyValue { 
    @ElementList(inline = true, required = false) 
    private List<ItemData> items; 

    @Text(required = false) 
    private String text; 
} 

ItemDataitem类。

但这不起作用。 该代码给我一个例外:

org.simpleframework.xml.core.TextException: Text annotation @org.simpleframework.xml.Text(data=false, empty=, required=false) on field 'text' private java.lang.String PropertyValue.text used with elements in class PropertyValue 

回答

1

我解决了这个问题!

我用了以下问题的答案:Deserializing an XML tag with text AND subtags using Retrofit

我创建的,因为我想(我的代码:-(抱歉)转换XML文件类:

public class PropertyValueConverter implements Converter<PropertyValue> { 
    @Override 
    public PropertyValue read(InputNode node) throws Exception { 
     PropertyValue propertyValue = new PropertyValue(); 
     List<ItemData> propertyValueItems = new ArrayList<>(); 
     String propertyValueText = ""; 

     InputNode itemNode = node.getNext("item"); 
     while (itemNode != null) { 
      String itemId = itemNode.getAttribute("id").getValue(); 
      ItemData itemData = new ItemData(); 
      itemData.setId(itemId); 
      propertyValueItems.add(itemData); 
      itemNode = node.getNext("id"); 
     } 

     if (propertyValueItems.size() == 0) { 
      propertyValueText = node.getValue(); 
     } 

     propertyValue.setItems(propertyValueItems); 
     propertyValue.setText(propertyValueText); 

     return propertyValue; 
    } 

    @Override 
    public void write(OutputNode node, PropertyValue value) throws Exception { 

    } 
} 

然后,我改变PropertyValue类:

@Root(strict = false) 
@Convert(value = PropertyValueConverter.class) 
public class PropertyValue { 
    private List<ItemData> items; 

    private String text; 

    public List<ItemData> getItems() { 
     return items; 
    } 

    public void setItems(List<ItemData> items) { 
     this.items = items; 
    } 

    public String getText() { 
     return text; 
    } 

    public void setText(String text) { 
     this.text = text; 
    } 
} 

然后我设置SimpleXML的转换器厂:

private static Strategy strategy = new AnnotationStrategy(); 
private static Serializer serializer = new Persister(strategy); 

private static Retrofit.Builder builder = 
     new Retrofit.Builder() 
       .baseUrl(API_BASE_URL) 
       .addConverterFactory(SimpleXmlConverterFactory.create(serializer)); 

所以,它适用于我。

3

我做到了用元素列表和入门

@ElementList(entry = "item", inline = true)

作品对我来说没有自定义转换器。 全班级:

@Root(name = "property") 
public class Property { 
    @ElementList(entry = "item", inline = true, required = false) 
    private List<Item> items; 

    @Text(required = false) 
    private String text; 
}