//realPath 被读取的非标准的xml文件路径 public void analysisXml(String realPath) throws ParserConfigurationException, SAXException, IOException, DocumentException, JAXBException { // 将不标准的xml转为字符串 String fileToString = FileUtils.readFileToString(new File(realPath)); // 将字符串加入声明及根节点以标注xml StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); sb.append(""); sb.append(fileToString); sb.append(""); //新生成的标准的xml的路径 String fileNameTmp = “c:/app/new.xml”; File file = new File(fileNameTmp); // 判断该文件是否存在,若不存在则创建一个xml文件 if (!file.exists()) { file.createNewFile(); } //将标准的xml字符串解析并转换成一个新的符合标准的xml outputXml(fileNameTmp, sb.toString()); //解析新的符合标准的xml并获取数据 analysisNewXml(fileNameTmp ); //将标准的xml字符串解析并转换成一个新的符合标准的xml //fileName:文件名 str:xml字符串 public static void outputXml(String fileName, String str) throws IOException { SAXReader saxReader = new SAXReader(); Document document; try { //将字符串读取成流形式并写入到xml文档中 document = saxReader.read(new ByteArrayInputStream(str .getBytes(“UTF-8”))); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter( new FileWriter(new File(fileName)), format); writer.write(document); writer.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }
//使用jaxb将xml解析为javabean对象 public Object xmlToBean(String xmlPath) throws JAXBException, IOException { JAXBContext context = JAXBContext.newInstance(Information.class); Unmarshaller unmarshaller = context.createUnmarshaller(); Object object = unmarshaller.unmarshal(new File(xmlPath)); return object; } //将javabean对象遍历存入数据库中 public void analysisNewXml(String xmlPath) throws JAXBException, IOException { //调用xml解析为javabean对象方法将xml转为对象 Object object = xmlToBean(xmlPath); Information documents = (Information) object; List documentList = documents.getDocuments(); //documentList对象就是xml中的根节点下的第一个子节点,jaxb获取值得方法可参考另一篇博客或他人博客 }
