我正在尝试使用简单 Java XML 解析器 (SJXP),但遇到了我需要解析为数据类的 XML 问题。
数据.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE SYSTEM "local-1.2.2.dtd" >
<data>
<article>
<field name="name" type="text">HOTELS</field>
<field name="name_de" type="text">HOTELS</field>
<field name="name_zh" type="text">酒店</field>
<field name="color" type="text">6,68,109,0.85</field>
<field name="textcolor" type="text">255,255,255,1</field>
</article>
<!-- 20000 more articles ... -->
</data>
我试图这样做:
xml处理程序.java
private Map<String, Category> categoryMap;
private XMLParser<Category> categoryParser = new XMLParser<Category>(
new DefaultRule<Category>(IRule.Type.CHARACTER, "/data/article") {
@Override
public void handleParsedCharacters(XMLParser<Category> parser, String text, Category category) {
Log.d("XmlHandler", "Hello");
if (category != null) {
categoryMap.put(category.getName(Category.LANG.EN), category);
Log.d("XmlHandler", "Saved category to map. New count="+categoryMap.values().size());
category.reset();
} else {
category = new Category();
Log.d("XmlHandler", "Creating a new category");
}
}
},
new CategoryNameRule()
);
private class CategoryNameRule extends DefaultRule<Category> {
private String nameKey = "";
public CategoryNameRule() {
super(Type.ATTRIBUTE, "/data/article/field", "name");
}
@Override
public void handleParsedAttribute(XMLParser parser, int index,
String value, Category category) {
nameKey = value;
}
@Override
public void handleParsedCharacters(XMLParser parser, String text, Category category) {
Log.d("XmlHandler", "Handling nameKey="+nameKey);
if(nameKey == null || nameKey.length() == 0){
return;
}else if( "name".equals(nameKey)){
category.setName(Category.LANG.EN, text);
}else if( "name_de".equals(nameKey)){
category.setName(Category.LANG.DE, text);
}else if( "name_zh".equals(nameKey)){
category.setName(Category.LANG.ZH, text);
}else if( "color".equals(nameKey)){
category.colorBackground = getConvertedColor(text);
}else if( "textcolor".equals(nameKey)){
category.colorForeground = getConvertedColor(text);
}
}
}
问题是我的哈希图在整个文档被解析后变成空的,我不知道为什么。我的猜测是我会结合 IRule.Type.CHARACTER 和 IRule.Type.ATTRIBUTE 但我不知道如何实现。
有什么想法/经验吗?