为了制作一个不错且可读的测试用例,我想解析一些手写的XML (从xmpp.org复制粘贴),将其转换为Stanza或XMLElement,然后继续进行实际测试。所以我想完全避免使用节生成器。
使用非阻塞XML解析器可以做到这一点吗?
发布于 2012-09-28 16:59:14
为了获得XMLElement解决方案,需要使用DefaultNonBlockingXMLReader并分配一个节监听器。诀窍是启动"stream",因此要测试的节的XML应该包装成类似于".....
代码:
private Stanza fetchStanza(String xml) throws SAXException {
try {
NonBlockingXMLReader reader = new DefaultNonBlockingXMLReader();
reader.setContentHandler(new XMPPContentHandler(new XMLElementBuilderFactory()));
XMPPContentHandler contentHandler = (XMPPContentHandler) reader.getContentHandler();
final ArrayList<Stanza> container = new ArrayList(); // just some container to hold stanza.
contentHandler.setListener(new XMPPContentHandler.StanzaListener() {
public void stanza(XMLElement element) {
Stanza stanza = StanzaBuilder.createClone(element, true, Collections.EMPTY_LIST).build();
if (!container.isEmpty()) {
container.clear(); // we need only last element, so clear the container
}
container.add(stanza);
}
});
IoBuffer in = IoBuffer.wrap(("<stream>" + xml + "</stream>").getBytes()); // the trick it to wrap xml to stream
reader.parse(in, CharsetUtil.UTF8_DECODER);
Stanza stanza = container.iterator().next();
return stanza;
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}https://stackoverflow.com/questions/12620292
复制相似问题