把字符串写入xml中

34 篇文章 0 订阅

public class DocXml {
public static void main(String[] args) {
String s1 = “

百度

”;
Document doc = str2Document(s1);
String fileName = “E:\learn\a.html”;
createXml(fileName, doc);

}


public static Document str2Document(String xmlStr) {
    Document doc = null;
    StringReader sr = new StringReader(xmlStr);
    InputSource is = new InputSource(sr);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
        doc = builder.parse(is);
    } catch (ParserConfigurationException e) {
        System.out.println("ParserConfiguration错误"+e);
    } catch (SAXException e) {
        System.out.println("SAX错误"+e);
    } catch (IOException e) {
        System.out.println("IO错误"+e);
    }
    return doc;
}


public synchronized static void createXml(String fileName, Document document) {
    System.out.println("============进入生成xml方法:" + new Date().toLocaleString() + "=================");
    try {
        // 判断文件是否存在,如存在就删掉它
        File file = new File(fileName);
        if (file.exists()) {
            file.delete();
            System.out.println("==============删除xml文件==============");
        }
        /\*\* 将document中的内容写入文件中 \*/
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(new FileOutputStream(fileName));
        transformer.transform(source, result);
        System.out.println("--------------------------------" + "更新 XML文件成功" + "-------------------------------------");
    } catch (final Exception exception) {
        System.out.println("更新" + fileName + "出错:"+exception);
    }
    System.out.println("============退出生成xml方法:" + new Date().toLocaleString() + "=================");
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值