标签:oms 锻炼 相对 image 技术 dom lips 工厂 jaxp
礼悟:
好好学习多思考,尊师重道存感恩。叶见寻根三二一,江河湖海同一体。
虚怀若谷良心主,愿行无悔给最苦。读书锻炼强身心,诚劝且行且珍惜。
jdk:1.8
xml:1.0
os:windows7 x64
ide:MyEclipse 2017
原本的XML
<?xml version="1.0" encoding="UTF-8"?> <shopping> <book> <name id="0001">灵枢</name> <price discount="90" originalPrice="100">90</price> <count>3</count> <comment>默认好评</comment> </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_E;
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.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
/**
* jaxp 在某一个标签下创建 有内容无属性的标签
*
* @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_E\\shopping.xml";
// Document -> import org.w3c.dom.Document;
Document document = builder.parse(uri);
// 得到所有的book元素
NodeList bookNodeList = document.getElementsByTagName("book");
// 在第一个book标签下,创建<sales>1000</sales>
Node firstBookNode = bookNodeList.item(0);
// 创建标签
Element salesNode = document.createElement("sales");
Text salesNodeText = document.createTextNode("1000");
// 把文本加到标签下
salesNode.appendChild(salesNodeText);
// 把标签加到标签下
firstBookNode.appendChild(salesNode);
// 回写操作,感觉好复杂呀
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>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>
虽然修改成功了,但是xml文件的格式改变了

xml优秀,值得学习。
学习资源:itcast和itheima视频库。如果您有公开的资源,可以分享给我的话,用您的资源学习也可以。
博文是观看视频后,融入思考写成的。博文好,是老师讲得好。博文坏,是 给最苦 没认真。
jaxp dom-appendChild 某一个标签下创建 有内容无属性的标签
标签:oms 锻炼 相对 image 技术 dom lips 工厂 jaxp
原文地址:http://www.cnblogs.com/jizuiku/p/7680674.html