java给xml添加多个相同节点_创建xml文件的缩进与添加相同子节点

//之前之所以添加的book节点会覆盖前面的book节点,是因为变量名都相同,这样的话自然下面的要替换上面的值

public static void main(String[] args) {

new TestXml().createXml();

}

public void createXml(){

DocumentBuilder db=getDocumentBuilder();

Document document=db.newDocument();

document.setXmlStandalone(true);

Element books=document.createElement("books");

document.appendChild(books);

//  添加多个节点

books.appendChild(getChildNode(document,"1","冰与火之歌","乔治马丁","39"));

books.appendChild(getChildNode(document,"2","安徒生童话","安徒生","29"));

TransformerFactory tff=TransformerFactory.newInstance();

try {

Transformer tf=tff.newTransformer();

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

//设置缩进量

tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

tf.transform(new DOMSource(document), new StreamResult(new File("lib/books1.xml")));

} catch (TransformerConfigurationException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (TransformerException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public DocumentBuilder getDocumentBuilder(){

DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();

DocumentBuilder db = null;

try {

db=dbf.newDocumentBuilder();

} catch (ParserConfigurationException e) {

e.printStackTrace();

}

return db;

}

public Element getChildNode(Document doc,String id,String name,String author,String price){

Element childNode=doc.createElement("book");

childNode.setAttribute("id", id);

childNode.appendChild(getChildNodeElement(doc,"name",name));

childNode.appendChild(getChildNodeElement(doc,"author",author));

childNode.appendChild(getChildNodeElement(doc,"price",price));

return childNode;

}

public Element getChildNodeElement(Document doc,String name,String text){

Element element=doc.createElement(name);

element.setTextContent(text);

return element;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值