XML通过jdom添加命名空间,添加声明头,添加节点前缀
前言
近期在对接海关公服系统,报文是xml格式的,并且报文节点上存在前缀和命名空间(没有深究到底干啥用);在网上找了很多资料,都是复制别人的粘贴成自己的成果,主要是还没有具体的解决方法,很无语了,我借鉴了几位网友的思路了解了一下jdom.Element,终于搞出来了,特此记录在此。
需求示例
解决方法
话不多说,给方法!
//根节点的空间
Namespace xmlns = Namespace.getNamespace("ceb", "http://www.chinaport.gov.cn/ceb");
//子节点空间
Namespace ns = Namespace.getNamespace("ceb", "http://www.chinaport.gov.cn/ceb");
Element root = new Element("CEB311Message",xmlns);
String uuid = UUID.randomUUID().toString();
root.setAttribute("version", "1.0");
root.setAttribute("guid", uuid.toUpperCase());
root.addNamespaceDeclaration(ns);
//Order节点
Element Order = new Element("Order",ns);
Element OrderHead = new Element("OrderHead",ns);
OrderHead.addContent(new Element("guid",ns).setText(uuid.toUpperCase()));
OrderHead.addContent(new Element("appType",ns).setText("1"));
OrderHead.addContent(new Element("appTime",ns).setText("20210728154004"));
OrderHead.addContent(new Element("appStatus",ns).setText("2"));
OrderHead.addContent(new Element("orderType",ns).setText("I"));
Order.addContent(OrderHead);
root.addContent(Order);
String xml = Util.elementToXml(root);
System.out.println(xml);