我使用Simple
XML来解析通信协议中使用的小型
XML文件.这一切都很好,但现在我正在实现协议的一部分,其中包括一种自由格式的XML.
例如,像这样的XML:
<telegram>
<config>
<foo>yes</foo>
<bar>no</bar>
</config>
</telegram>
foo和bar将来可能会发生变化,或者可能会添加一个元素baz,而无需触及解析代码.我想使用类似的结构在Java中访问这些元素
tree.getConfig().get("bar"); // returns "no"
我可以使用SimpleXML来解析它吗?我查看了文档,但找不到我需要的东西.
最佳答案
Can I use SimpleXML to parse that?
不是开箱即用 – 但写一个Converter就可以了.
@Root(name = "telegram")
@Convert(Telegram.TelegramConverter.class) // Requires AnnotationStrategy
public class Telegram
{
private Map<String, String> config;
public String get(String name)
{
return config.get(name);
}
public Map<String, String> getConfig()
{
return config;
}
// ...
@Override
public String toString()
{
return "Telegram{" + "config=" + config + '}';
}
static class TelegramConverter implements Converter<Telegram>
{
@Override
public Telegram read(InputNode node) throws Exception
{
Telegram t = new Telegram();
final InputNode config = node.getNext("config");
t.config = new HashMap<>();
// Iterate over config's child nodes and put them into the map
InputNode cfg = config.getNext();
while( cfg != null )
{
t.config.put(cfg.getName(), cfg.getValue());
cfg = config.getNext();
}
return t;
}
@Override
public void write(OutputNode node, Telegram value) throws Exception
{
// Implement if you need serialization too
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
用法:
final String xml = "<telegram>\n"
+ " <config>\n"
+ " <foo>yes</foo>\n"
+ " <bar>no</bar>\n"
+ " <baz>maybe</baz>\n" // Some "future element"
+ " </config>\n"
+ "</telegram>";
/*
* The AnnotationStrategy is set here since it's
* necessary for the @Convert annotation
*/
Serializer ser = new Persister(new AnnotationStrategy());
Telegram t = ser.read(Telegram.class, xml);
System.out.println(t);
结果:
Telegram{config={bar=no, foo=yes, baz=maybe}}