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

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

以下:

/**
     * <XML字符串转换成XML Document >
     * <功能详细描述>
     * @param sXml
     * @return
     * @see [类、类#方法、类#成员]
     */
    public Document changeStringToXML(String sXml)
    {
        StringReader sr = new StringReader(sXml);
        InputSource is = new InputSource(sr);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(is);
	return doc;
    }


将XML生成在指定路径:

/**
     * 生成文件
     * @param path
     * @param doc
     * @return  -1:生成xml出错    0:创建成功   1:所要上报的文件生成
     */
    public int writeXML(String path,Document doc)
    {
        File markFile = new File(path);
        if (markFile.exists())
        {
            return 1;
        }
        FileOutputStream fos;
        try
        {
            fos = new FileOutputStream(path);
        }
        catch (FileNotFoundException e)
        {
            logger.debug("数据上报XML文件输出出错:系统找不到指定路径");
            return -1;
        }
        OutputStreamWriter outwriter;
        try
        {
            outwriter = new OutputStreamWriter(fos,"UTF-8");
            Source sorce = new DOMSource(doc);
            Result result = new StreamResult(outwriter);
            Transformer trans;
            try
            {
                trans = TransformerFactory.newInstance().newTransformer();
                trans.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
                trans.transform(sorce,result);
                try
                {
                    fos.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                return 0;
            }
            catch (TransformerConfigurationException e)
            {
                e.printStackTrace();
                return -1;
            }
            catch (TransformerFactoryConfigurationError e)
            {
                e.printStackTrace();
                return -1;
            }
            catch (TransformerException e)
            {
                e.printStackTrace();
                return -1;
            }
        }
        catch (UnsupportedEncodingException e1)
        {
            e1.printStackTrace();
            return -1;
        }
        
    }
原文链接:https://www.f2er.com/xml/295101.html

猜你在找的XML相关文章