您的位置:首页

jaxp dom-setTextContent xml中修改标签的文本内容

2017-10-17 11:30 369 查看
礼悟:
   公恒学思合行悟,尊师重道存感恩。叶见寻根三返一,江河湖海同一体。
虚怀若谷良心主,愿行无悔给最苦。读书锻炼养身心,诚劝且行且珍惜。

jdk:1.8
xml:1.0
os:windows7 x64
ide:MyEclipse 2017


原本的XML

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<shopping>

<book>
<name id="0001">灵枢</name>
<price discount="90" originalPrice="100">90</price>
<count>3</count>
<comment>默认好评</comment>
<sales>1000</sales>
</book>

<book>
<name id="0002">素问</name>
<price discount="90" originalPrice="200">180</price>
<count>5</count>
<comment>默认好评</comment>
</book>

<book>
<name id="0003">伤寒杂病论</name>
<price discount="90" originalPrice="300">270</price>
<count>7</count>
<comment>默认好评</comment>
</book>

</shopping>


代码

package jizuiku.xml_F;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
* jaxp 修改xml中一个标签的文本内容
*
* @author 给最苦
* @version V17.10.10
*/
public class JaxpDemo {
public static void main(String[] args) throws Exception {
// 创建解析器工厂
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

// 创建解析器
DocumentBuilder builder = builderFactory.newDocumentBuilder();

// 解析xml返回document
// uri为相对路径
String uri = "src\\jizuiku\\xml_F\\shopping.xml";
// Document -> import org.w3c.dom.Document;
Document document = builder.parse(uri);

// 得到所有的sales元素
NodeList salesNodeList = document.getElementsByTagName("sales");

// 修改第一个sales标签的内容
Node firstSalesNode = salesNodeList.item(0);
firstSalesNode.setTextContent("2000");

// 回写操作,感觉好复杂呀
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();

transformer.transform(new DOMSource(document), new StreamResult(uri));

/*
* 别看上面的程序很简单都是套路,但是 给最苦 在写的时候 也是经历了一些困难的
*
*/
}
}


修改后的XML

<?xml version="1.0" encoding="UTF-8" standalone="no"?><shopping>

<book>
<name id="0001">灵枢</name>
<price discount="90" originalPrice="100">90</price>
<count>3</count>
<comment>默认好评</comment>
<sales>2000</sales>
</book>

<book>
<name id="0002">素问</name>
<price discount="90" originalPrice="200">180</price>
<count>5</count>
<comment>默认好评</comment>
</book>

<book>
<name id="0003">伤寒杂病论</name>
<price discount="90" originalPrice="300">270</price>
<count>7</count>
<comment>默认好评</comment>
</book>

</shopping>


xml优秀,值得学习。
学习资源:itcast和itheima视频库。如果您有公开的资源,可以分享给我的话,用您的资源学习也可以。
博文是观看视频后,融入思考写成的。博文好,是老师讲得好。博文坏,是 给最苦 没认真。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐