• 使用Java创建xml文件


    package org.xml.example;
    
    import java.io.File;
    import java.io.StringWriter;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    
    public class Demo3 {
        public static void main(String[] args) {
            
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder;
            try {
                builder = documentBuilderFactory.newDocumentBuilder();
                Document document = builder.newDocument();
                Element root = document.createElement("language");
                root.setAttribute("cat", "it");
                Element lan1 = document.createElement("lan");
                lan1.setAttribute("id" , "1");
                Element name1 = document.createElement("name");
                name1.setTextContent("java");
                Element ide1 = document.createElement("ide");
                ide1.setTextContent("myeclipse");
                
                lan1.appendChild(name1);
                lan1.appendChild(ide1);
                root.appendChild(lan1);
                
                document.appendChild(root);
                
                //创建转换工厂,然后将创建的document转换输出到文件中或控制台
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                transformer.transform(new DOMSource(document), new StreamResult(new File("newXml.xml")));
                
           //将document中的信息转换为字符串输出到控制台中 StringWriter stringWriter
    = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(stringWriter)); System.out.println(stringWriter.toString()); } catch (Exception e) { e.printStackTrace(); } } }

    该文件创建放在项目中路径中

    成功的结果:

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <language cat="it">
        <lan id="1">
            <name>java</name>
            <ide>myeclipse</ide>
        </lan>
    </language>
  • 相关阅读:
    如果因特网中的所有链路都提供可靠的交付服务,TCP可靠传输服务是多余的吗?
    编译运行java程序出现Exception in thread "main" java.lang.UnsupportedClassVersionError: M : Unsupported major.minor version 51.0
    chrome浏览器插件的开启快捷键
    sqlzoo练习题答案
    2019Falg
    python绘图踩的坑
    精益数据分析--测试分析
    np.random的随机数函数
    numpy中文件的存储和读取-嵩天老师笔记
    喜欢的话
  • 原文地址:https://www.cnblogs.com/myfaith-feng/p/9213896.html
Copyright © 2020-2023  润新知