java中xml写入_java写入xml

package com.cn;

import java.io.FileInputStream;

import java.io.FileWriter;

import java.io.IOException;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

public class ReadXml {

public ReadXml() {

// 得到Dom解析工厂

DocumentBuilderFactory domfactory = DocumentBuilderFactory

.newInstance();

try {

// 取得dom解析器

DocumentBuilder docBilder = domfactory.newDocumentBuilder();

// 将xml文件读入输入流

InputStream in = new FileInputStream("F://tes.xml");

FileWriter fw = new FileWriter("F://waa.xml");

// 解析xml输入流

Document doc = docBilder.parse(in);

// 在DOM中取得xml的根节点

Element root = doc.getDocumentElement();

// 得到子节点

NodeList students = root.getChildNodes();

// 遍历子节点

if (students != null) {

for (int i = 0; i < students.getLength(); i++) {

fw.write("<?xml version=\"1.0\"encoding=\"UTF-8\"?>");

Node student = students.item(i);

// 判断是否有属性

if (student.getNodeType() == Node.ELEMENT_NODE) {

fw.write("\n");

String sn = student.getAttributes().getNamedItem("sn")

.getNodeValue();

fw.write("\n  ");

System.out.println("sn-------------"+sn);

}

// 轮训子节点

for (Node node = student.getFirstChild(); node != null; node = node

.getNextSibling()) {

if (node.getNodeType() == Node.ELEMENT_NODE) {

if (node.getNodeName().equals("name")) {

String name = node.getNodeValue();

System.out.println("name--------------" + name);

String name1 = node.getFirstChild()

.getNodeValue();

System.out.println("name1--------------"

+ name1);

fw.write("\n"+name1+"\n");

}

if (node.getNodeName().equals("age")) {

String age = node.getFirstChild()

.getNodeValue();

System.out.println("age---------" + age);

fw.write("\n"+age+"\n");

fw.write("\n");

}

}

}

}

}

fw.close();

} catch (Exception e) {

e.printStackTrace();

}

}

public static void main(String args[]) {

ReadXml rd = new ReadXml();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值