场景一:快速定位到某一个具体的节点,并获取节点数据
public static Node getNode(Document doc,String path) { if (doc != null) { if (doc.selectSingleNode(path) != null) { return doc.selectSingleNode(path); } } return null; }
场景二:获取某个列表类型的节点的数据
public static List<Node> getNodeList(Document doc,String path) { if (doc != null) { if (doc.selectNodes(path) != null) { return doc.selectNodes(path); } } return null; }
场景三:获取指定节点的数据,并将数据注入到指定的JavaBean中(前提是JavaBean已经进行了注解的处理)
调用示例:
getXmlNode("xml格式的string类型",“指定节点的路径”,"想要转换成的javaBean类","节点替换前的名称","节点替换后的名称")
getXmlNode(xml,"//item/degreeInfo",Student.class,"degreeInfo","personBaseInfo");
public static Object getXmlNode(String xml,String path,Class<?> cls,String... jss) { Document doc; String strXml = null; try { doc = DocumentHelper.parseText(xml); if (doc != null) { if (doc.selectSingleNode(xpath) != null) { strXml = doc.selectSingleNode(path).asXML(); } } if (jss != null && jss.length >= 2 && StringUtils.hasLength(strXml)) { return XmlBase.xmlToBean(cls,strXml.replace(jss[0],jss[1])); } else if (StringUtils.hasLength(strXml)) { return XmlBase.xmlToBean(cls,strXml); } } catch (DocumentException e) { e.printStackTrace(); } return null; }
场景四:获取xml某列表节点数据,并注入到相应的JavaBean中(前提是JavaBean已经进行了注解的处理)
getXmlNode("xml格式的string类型",JavaBean列表对象,"节点替换后的名称")
getXmlNode(xml,list,"personBaseInfo");
public static void getXmlNode(String xml,String xpath,List list,String... jss) { Document doc; String strXml = null; try { doc = DocumentHelper.parseText(xml); if (doc != null) { if (doc.selectNodes(xpath) != null) { List<Node> lst= doc.selectNodes(xpath); for(Node l:lst){ strXml=l.asXML(); if (jss != null && jss.length >= 2 && StringUtils.hasLength(strXml)) { list.add(XmlBase.xmlToBean(cls,jss[1]))); }else{ list.add(XmlBase.xmlToBean(cls,strXml)); } } } } } catch (DocumentException e) { e.printStackTrace(); } }原文链接:https://www.f2er.com/xml/295831.html