public class test{
private static final Map<String, JAXBContext> contextCache = new ConcurrentHashMap<>();
private void testXml(String xml) {
AbstractMX msg = getAbstractMX(xml, (Class)MxCamt00200102.class, new Class[] {MxCamt00200102.class, BusinessAppHdrV02.class });
MxCamt00200102 document = (MxCamt00200102)abstractMX;
System.out.println("报文ID:"+document.getPacs00200102().getGrpHdr().getMsgId());
}
public AbstractMX getAbstractMX(String xml, Class<? extends AbstractMX> targetClass, Class... classesToBeBound) {
xml = "<message>" + xml + "</message>";
Class<?>[] classes = new Class[] { MxCamt00200102.class
//可根据需要设置多个消息类
};
try {
JAXBContext jaxbContext = getJAXBContext(targetClass.getName(), classesToBeBound);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty("jaxb.encoding", "UTF-8");
marshaller.setProperty("jaxb.formatted.output", Boolean.valueOf(true));
marshaller.setProperty("jaxb.fragment", Boolean.valueOf(false));
marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper() {
public String getPreferredPrefix(String namespaceuri, String suggestion, boolean requirePrefix) {
if (namespaceuri.equals("urn:iso:std:iso:20022:tech:xsd:pacs.002.001.02"))
return "pacs";
if (namespaceuri.equals("urn:iso:std:iso:20022:tech:xsd:head.001.001.02"))
return "head";
return suggestion;
}
});
MxReadParams mxReadParams = new MxReadParams(new MxReadConfiguration(new MxWriteConfiguration(jaxbContext)));
AbstractMX abstractMX = MxReadImpl.parse(targetClass, xml, classes, mxReadParams);
return abstractMX;
} catch (JAXBException e) {
return null;
}
}
private static JAXBContext getJAXBContext(String packageName, Class... classesToBeBound) throws JAXBException {
JAXBContext jaxbContext = contextCache.get(packageName);
if (jaxbContext == null) {
log.debug("Creating new JAXBContext instance for package: " + packageName);
jaxbContext = JAXBContext.newInstance(classesToBeBound);
contextCache.put(packageName, jaxbContext);
}
return jaxbContext;
}
}
根据解析报文消息类,可以根据需求自定义标签。当然在添加多个消息类时,依然需要通过报文类型去校验。通过if条件进行区分。我也通过AI去搜集过更通用,更便捷的解析方式,想要减少非必要的重复性代码编写。奈何本人技术有限,暂时还没有找到更便捷的方式。哪位大神若是看到了,还请指点一二。
1万+

被折叠的 条评论
为什么被折叠?



