[英]SimpleXML: element with elements list or text
我必須解析一個可以是兩種類型的XML文件:
<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;
}
ItemData
是item
類。
但這是行不通的。 該代碼給了我一個例外:
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
我使用ElementList和entry做到了
@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;
}
我解決了問題!
我使用以下問題答案: 使用Retrofit反序列化帶有文本和子標簽的XML標簽
我創建了一個類,可以根據需要轉換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));
因此,它為我工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.