我使用SimpleXML来解析通信协议中使用的小型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?
@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}}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。