zoukankan      html  css  js  c++  java
  • Java代码之《生成XMl文件》

    话不多说,代码如下:

       public class BuildXmlUtil {
        
            public static void main(String[] args) throws Exception {
                buildxml();
            }
            
            public static void buildxml() throws ParserConfigurationException, TransformerException{
                
                //step1:获得一个DocumentBuilderFactory
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                //step2:获得一个DocumentBuilder
                DocumentBuilder db = factory.newDocumentBuilder();
                //step3:新建一个Document对象
                Document document = db.newDocument();
                //step4:创建一个根节点
                Element rootElement = document.createElement("engineering");
                for (int i=0;i<3;i++){
                        //step5:创建一个节点
                        Element person = document.createElement("engineering");
                        //step6:为该节点设定属性
                        person.setAttribute("id", "id_");
                        Element name = document.createElement("name");
                        //为节点设定文本内容    
                        name.setTextContent("name_");
                        Element author = document.createElement("author");
                        author.setTextContent("author_");
                        Element addressUrl = document.createElement("addressUrl");
                        addressUrl.setTextContent("addressUrl_");
                    person.appendChild(name);
                    person.appendChild(author);
                    person.appendChild(addressUrl);
                    //step7:为某一元素节点设立子节点
                    rootElement.appendChild(person);
                }
                    //step8:把刚刚建立的根节点添加到document对象中
                    document.appendChild(rootElement);
                    //step9:获得一个TransformerFactory对象
                    TransformerFactory transformerFactory = TransformerFactory.newInstance();
                    //step10:获得一个Transformer对象
                    Transformer transformer = transformerFactory.newTransformer();
                    //step11:把document对象用一个DOMSource对象包装起来
                    Source xmlSource = new DOMSource(document);
                    System.out.println(xmlSource);
                    //step12:建立一个存储目标对象
                    Result outputTarget = new StreamResult(new File("C:\Users\yc\Desktop\persons.xml"));
                    //step13:生成相应的xml文件
                    transformer.transform(xmlSource,outputTarget); 
                    
                }

    }

  • 相关阅读:
    Q:简单实现URL只能页面跳转,禁止直接访问
    Q:elementUI中tree组件动态展开
    一个切图仔的 JS 笔记
    一个切图仔的HTML笔记
    一个切图仔的 CSS 笔记
    GnuPG使用笔记
    SQL Svr 2012 Enterprise/Always-on节点连接超时导致节点重启——case分享
    网卡配置文件备份在原目录下引起网络配置异常
    python培训
    service脚本的写法
  • 原文地址:https://www.cnblogs.com/lwh0206/p/7866369.html
Copyright © 2011-2022 走看看