XML字符串转换成XML Document对象,并生成在指定路径

前端之家收集整理的这篇文章主要介绍了XML字符串转换成XML Document对象,并生成在指定路径前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

以下:

  1. /**
  2. * <XML字符串转换成XML Document >
  3. * <功能详细描述>
  4. * @param sXml
  5. * @return
  6. * @see [类、类#方法、类#成员]
  7. */
  8. public Document changeStringToXML(String sXml)
  9. {
  10. StringReader sr = new StringReader(sXml);
  11. InputSource is = new InputSource(sr);
  12. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  13. DocumentBuilder builder = factory.newDocumentBuilder();
  14. Document doc = builder.parse(is);
  15. return doc;
  16. }


将XML生成在指定路径:

  1. /**
  2. * 生成文件
  3. * @param path
  4. * @param doc
  5. * @return -1:生成xml出错 0:创建成功 1:所要上报的文件生成
  6. */
  7. public int writeXML(String path,Document doc)
  8. {
  9. File markFile = new File(path);
  10. if (markFile.exists())
  11. {
  12. return 1;
  13. }
  14. FileOutputStream fos;
  15. try
  16. {
  17. fos = new FileOutputStream(path);
  18. }
  19. catch (FileNotFoundException e)
  20. {
  21. logger.debug("数据上报XML文件输出出错:系统找不到指定路径");
  22. return -1;
  23. }
  24. OutputStreamWriter outwriter;
  25. try
  26. {
  27. outwriter = new OutputStreamWriter(fos,"UTF-8");
  28. Source sorce = new DOMSource(doc);
  29. Result result = new StreamResult(outwriter);
  30. Transformer trans;
  31. try
  32. {
  33. trans = TransformerFactory.newInstance().newTransformer();
  34. trans.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
  35. trans.transform(sorce,result);
  36. try
  37. {
  38. fos.close();
  39. }
  40. catch (IOException e)
  41. {
  42. e.printStackTrace();
  43. }
  44. return 0;
  45. }
  46. catch (TransformerConfigurationException e)
  47. {
  48. e.printStackTrace();
  49. return -1;
  50. }
  51. catch (TransformerFactoryConfigurationError e)
  52. {
  53. e.printStackTrace();
  54. return -1;
  55. }
  56. catch (TransformerException e)
  57. {
  58. e.printStackTrace();
  59. return -1;
  60. }
  61. }
  62. catch (UnsupportedEncodingException e1)
  63. {
  64. e1.printStackTrace();
  65. return -1;
  66. }
  67. }

猜你在找的XML相关文章