java xml w3c_java 解析xml文档之w3c模式解析demo

public class W3cTest {

/**

解析xml的几种方法

*/

public static void main(String[] args) {

System.out.println("执行!");

try {

creatXml();

} catch (Exception e) {

e.printStackTrace();

}

try {

resolving();

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

//创建xml文档并创建节点

public static void creatXml() throws Exception{

//创建 解析器工厂

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

//创建 xml解析器

DocumentBuilder db = dbf.newDocumentBuilder();

//获取要操作的document对象

Document doucment = db.newDocument();

//设置xml版本

doucment.setXmlVersion("1.0");

//创建跟节点

Element root = doucment.createElement("heros");

//将根节点添加到doc对象

doucment.appendChild(root);

//声明 数组

String nameList[] = {"李奇微","麦克阿瑟","周笔畅","刘德华","赵本山","刘能","曹操"};

String sexList[] = {"男","女"};

//循环写入数据

for (int i = 0; i < 20; i++) {

//创建根节点元素

Element rootElement = doucment.createElement("hreo");

//声明参数

String id = "";

//生成9位的随机id

for (int j = 0; j < 9; j++) {

id += new Random().nextInt(8)+1;

}

//设置元素节点的属性

rootElement.setAttribute("id", id);

//添加元素到根节点中

root.appendChild(rootElement);

//设置元素节点

Element name = doucment.createElement("姓名");

Element sex = doucment.createElement("性别");

Element age = doucment.createElement("age");

//给元素节点赋值

name.setTextContent(nameList[new Random().nextInt(nameList.length)]);

sex.setTextContent(sexList[new Random().nextInt(sexList.length)]);

age.setTextContent(new Random().nextInt(20)+20+"");

String tel = "";

for(int k = 0 ; k < 7 ; k++){

tel += new Random().nextInt(9);

}

//添加节点到元素节点中

rootElement.appendChild(name);

rootElement.appendChild(sex);

rootElement.appendChild(age);

}

//把doucment 映射到文件

TransformerFactory tff = TransformerFactory.newInstance();

Transformer tf = tff.newTransformer();

//生成xml文件

File file = new File("d:\\abc\\w3c.xml");

//判断有文件,没有就创建

if(file.exists()){

file.createNewFile();

}

//设置是否添加空格

tf.setOutputProperty(OutputKeys.INDENT,"yes");

//输出文件格式!!!

tf.setOutputProperty(OutputKeys.ENCODING, "utf-8");

//输出文件

tf.transform(new DOMSource(doucment), new StreamResult(new FileOutputStream(file)));

//测试输出xml文件路径

System.out.println(file.getAbsolutePath());

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值