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); 
                
            }

}

转载于:https://www.cnblogs.com/lwh0206/p/7866369.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值