大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
// 给你一个例子,你参考下
创新互联专注为客户提供全方位的互联网综合服务,包含不限于网站设计制作、网站制作、应县网络推广、小程序制作、应县网络营销、应县企业策划、应县品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;创新互联为所有大学生创业者提供应县建站搭建服务,24小时服务热线:18982081108,官方网址:www.cdcxhl.com
// java通过dom读写xml文件
/*要读的xml文件
?xml version="1.0" encoding="GB2312"?
学生花名册
学生 性别 = "男"
姓名李华/姓名
年龄14/年龄
/学生
学生 性别 = "男"
姓名张三/姓名
年龄16/年龄
/学生
/学生花名册
*/
package xml;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Iterator;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
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;
public class DomTest {
Vector students_Vector;
private Vector readXMLFile(String file) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(file); // 获取到xml文件
// 下面开始读取
Element root = doc.getDocumentElement(); // 获取根元素
NodeList students = root.getElementsByTagName_r("学生");
students_Vector = new Vector();
for (int i = 0; i students.getLength(); i++) {
// 一次取得每一个学生元素
Element ss = (Element) students.item(i);
// 创建一个学生的实例
student stu = new student();
stu.setSex(ss.getAttribute("性别"));
NodeList names = ss.getElementsByTagName_r("姓名");
Element e = (Element) names.item(0);
Node t = e.getFirstChild();
stu.setName(t.getNodeValue());
NodeList ages = ss.getElementsByTagName_r("年龄");
e = (Element) ages.item(0);
t = e.getFirstChild();
stu.setAge(Integer.parseInt(t.getNodeValue()));
students_Vector.add(stu);
}
return students_Vector;
}
// 写入xml文件
public static void callWriteXmlFile(Document doc, Writer w, String encoding) {
try {
Source source = new DOMSource(doc);
Result result = new StreamResult(w);
Transformer xformer = TransformerFactory.newInstance()
.newTransformer();
xformer.setOutputProperty(OutputKeys.ENCODING, encoding);
xformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
private void writeXMLFile(String outfile) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = dbf.newDocumentBuilder();
} catch (Exception e) {
}
Document doc = builder.newDocument();
Element root = doc.createElement("学生花名册");
doc.appendChild(root); // 将根元素添加到文档上
// 获取学生信息
for (int i = 0; i students_Vector.size(); i++) {
student s = (student) students_Vector.get(i);
// 创建一个学生
Element stu = doc.createElement("学生");
stu.setAttribute("性别", s.getSex());
root.appendChild(stu);// 添加属性
// 创建文本姓名节点
Element name = doc.createElement("姓名");
stu.appendChild(name);
Text tname = doc.createTextNode(s.getName());
name.appendChild(tname);
//创建文本年龄节点
Element age = doc.createElement("年龄");
stu.appendChild(age); // 将age添加到学生节点上
Text tage = doc.createTextNode(String.valueOf(s.getAge()));
age.appendChild(tage); // 将文本节点放在age节点上
}
try {
FileOutputStream fos = new FileOutputStream(outfile);
OutputStreamWriter outwriter = new OutputStreamWriter(fos);
// ((XmlDocument)doc).write(outwriter); //出错!
callWriteXmlFile(doc, outwriter, "gb2312");
outwriter.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
String str = "xml/student.xml";
DomTest t = new DomTest();
try {
Vector v = t.readXMLFile(str);
Iterator it = v.iterator();
while (it.hasNext()) {
student s = (student) it.next();
System.out.println(s.getName() + "\t" + s.getAge() + "\t"
+ s.getSex());
}
} catch (Exception e) {
e.printStackTrace();
}
String outfile = "xml/stucopy.xml";
t.writeXMLFile(outfile);
}
}
class student{
private String sex;
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void setSex(String s){sex=s;}
public String getSex(){return sex;}
public void setName(String n){name=n;}
public String getName(){return name;}
}
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.output.XMLOutputter;
public class JavaXML {
public void BuildXMLDoc() throws IOException, JDOMException {
// 创建根节点 list;
Element root = new Element("list");
// 根节点添加到文档中;
Document Doc = new Document(root);
// 此处 for 循环可替换成 遍历 数据库表的结果集操作;
for (int i = 0; i 5; i++) {
// 创建节点 user;
Element elements = new Element("company");
// 给 company 节点添加属性 id;
elements.setAttribute("id", "" + i);
// 给 company 节点添加子节点并赋值
// new Element("company_name")中的 "company_name" 替换成表中相应字段,setText("name")中 "name 替换成表中记录值;
elements.addContent(new Element("company_name").setText("name" + i));
elements.addContent(new Element("company_email").setText("@" + i+ ".com"));
// 给父节点list添加company子节点;
root.addContent(elements);
}
XMLOutputter XMLOut = new XMLOutputter();
// 输出company_list.xml文件;
XMLOut.output(Doc, new FileOutputStream("company_list.xml"));
}
/**
* 主方法用于测试
* @param args
*/
public static void main(String[] args) {
try {
JavaXML javaXML = new JavaXML();
javaXML.BuildXMLDoc();
} catch (Exception e) {
e.printStackTrace();
}
}
2./**
1. * desciption:java create xml file
2. * author:maomao
3. * datetime:2007/04/04 23:42
4. */
5.
6.package com.xh.xml;
1.
2.import java.io.FileOutputStream;
1.import java.io.IOException;
1.import org.jdom.Document;
1.import org.jdom.Element;
1.import org.jdom.JDOMException;
1.import org.jdom.output.XMLOutputter;
1.
2.public class Java2XML {
1.
2. public void BuildXMLDoc() throws IOException, JDOMException {
3.
4. // 创建根节点 list;
5. Element root = new Element("list");
6.
7. // 根节点添加到文档中;
8. Document Doc = new Document(root);
9.
10. // 此处 for 循环可替换成 遍历 数据库表的结果集操作;
11. for (int i = 0; i 5; i++) {
12.
13. // 创建节点 user;
14. Element elements = new Element("user");
15.
16. // 给 user 节点添加属性 id;
17. elements.setAttribute("id", "" + i);
18.
19. // 给 user 节点添加子节点并赋值;
20. // new Element("name")中的 "name" 替换成表中相应字段,setText("xuehui")中 "xuehui 替换成表中记录值;
21. elements.addContent(new Element("name").setText("xuehui"));
22. elements.addContent(new Element("age").setText("28"));
23. elements.addContent(new Element("sex").setText("Male"));
24.
25. // 给父节点list添加user子节点;
26. root.addContent(elements);
27.
28. }
29. XMLOutputter XMLOut = new XMLOutputter();
30.
31. // 输出 user.xml 文件;
32. XMLOut.output(Doc, new FileOutputStream("user.xml"));
33. }
34.
35. public static void main(String[] args) {
36. try {
37. Java2XML j2x = new Java2XML();
38. System.out.println("生成 mxl 文件...");
39. j2x.BuildXMLDoc();
40. } catch (Exception e) {
41. e.printStackTrace();
42. }
43. }
44.
45.}
生成结果:
# ?xml version="1.0" encoding="UTF-8"?
# list
# user id="0"
# namexuehui/name
# age28/age
# sexMale/sex
# /user
# user id="1"
# namexuehui/name
# age28/age
# sexMale/sex
# /user
# user id="2"
# namexuehui/name
# age28/age
# sexMale/sex
# /user
# user id="3"
# namexuehui/name
# age28/age
# sexMale/sex
# /user
# user id="4"
# namexuehui/name
# age28/age
# sexMale/sex
# /user
# /list
你可以参考一下链接,然后拷贝代码,这里我直接拷贝带上行号。
root.element("time").setText("测试");这句是否有误?
root.element("time").getFirstChild().setText("测试");试试看
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.*;
import javax.xml.xpath.*;
public class Test {
public static void main(String[] args) {
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
Element theBook=null, theElem=null, root=null;
try {
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder db=factory.newDocumentBuilder();
Document xmldoc=db.parse(new File("Test1.xml"));
root=xmldoc.getDocumentElement();
theBook=(Element) selectSingleNode("/books/book[name='哈里波特']", root);
System.out.println("--- 查询找《哈里波特》 ----");
Element nameNode=(Element)theBook.getElementsByTagName("price").item(0);
String name=nameNode.getFirstChild().getNodeValue();
System.out.println(name);
output(theBook);
System.out.println("=============selectSingleNode(books/book[name='哈里波特'], root)==================");
//--- 新建一本书开始 ----
theBook=xmldoc.createElement("book");
theElem=xmldoc.createElement("name");
theElem.setTextContent("新书");
theBook.appendChild(theElem);
theElem=xmldoc.createElement("price");
theElem.setTextContent("20");
theBook.appendChild(theElem);
theElem=xmldoc.createElement("memo");
theElem.setTextContent("新书的更好看。");
theBook.appendChild(theElem);
root.appendChild(theBook);
System.out.println("--- 新建一本书开始 ----");
output(xmldoc);
System.out.println("==============================");
//--- 新建一本书完成 ----
//--- 下面对《哈里波特》做一些修改。 ----
//--- 查询找《哈里波特》----
//--- 此时修改这本书的价格 -----
theBook.getElementsByTagName("price").item(0).setTextContent("15");//getElementsByTagName返回的是NodeList,所以要跟上item(0)。另外,getElementsByTagName("price")相当于xpath的".//price"。
System.out.println("--- 此时修改这本书的价格 ----");
output(theBook);
//--- 另外还想加一个属性id,值为B01 ----
theBook.setAttribute("id", "B01");
System.out.println("--- 另外还想加一个属性id,值为B01 ----");
output(theBook);
//--- 对《哈里波特》修改完成。 ----
//--- 要用id属性删除《三国演义》这本书 ----
theBook=(Element) selectSingleNode("/books/book[@id='B02']", root);
System.out.println("--- 要用id属性删除《三国演义》这本书 ----");
output(theBook);
theBook.getParentNode().removeChild(theBook);
System.out.println("--- 删除后的XML ----");
output(xmldoc);
//--- 再将所有价格低于10的书删除 ----
NodeList someBooks=selectNodes("/books/book[price10]", root);
System.out.println("--- 再将所有价格低于10的书删除 ---");
System.out.println("--- 符合条件的书有 "+someBooks.getLength()+"本。 ---");
for(int i=0;isomeBooks.getLength();i++) {
someBooks.item(i).getParentNode().removeChild(someBooks.item(i));
}
output(xmldoc);
saveXml("Test1_Edited.xml", xmldoc);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void output(Node node) {//将node的XML字符串输出到控制台
TransformerFactory transFactory=TransformerFactory.newInstance();
try {
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty("encoding", "gb2312");
transformer.setOutputProperty("indent", "yes");
DOMSource source=new DOMSource();
source.setNode(node);
StreamResult result=new StreamResult();
result.setOutputStream(System.out);
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
public static Node selectSingleNode(String express, Object source) {//查找节点,并返回第一个符合条件节点
Node result=null;
XPathFactory xpathFactory=XPathFactory.newInstance();
XPath xpath=xpathFactory.newXPath();
try {
result=(Node) xpath.evaluate(express, source, XPathConstants.NODE);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return result;
}
public static NodeList selectNodes(String express, Object source) {//查找节点,返回符合条件的节点集。
NodeList result=null;
XPathFactory xpathFactory=XPathFactory.newInstance();
XPath xpath=xpathFactory.newXPath();
try {
result=(NodeList) xpath.evaluate(express, source, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return result;
}
public static void saveXml(String fileName, Document doc) {//将Document输出到文件
TransformerFactory transFactory=TransformerFactory.newInstance();
try {
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");
DOMSource source=new DOMSource();
source.setNode(doc);
StreamResult result=new StreamResult();
result.setOutputStream(new FileOutputStream(fileName));
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
XML:
?xml version="1.0" encoding="GBK"?
books
book
name哈里波特/name
price10/price
memo这是一本很好看的书。/memo
/book
book id="B02"
name三国演义/name
price10/price
memo四大名著之一。/memo
/book
book id="B03"
name水浒/name
price6/price
memo四大名著之一。/memo
/book
book id="B04"
name红楼/name
price5/price
memo四大名著之一。/memo
/book
/books
一个XML文档,可以先构造一个DOM,然后将DOM转化为xml序列,输出或者生成文件。package test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
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;
public class Test {
public static void generate(){
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
document.setXmlVersion("1.0");
document.setXmlStandalone(true);
Element root = document.createElement_x("MobileNet"); //创建根节点
document.appendChild(root); //将根节点添加到Document对象中
Element pageElement = document.createElement_x("page"); //设置第一个page元素到
pageElement.setAttribute("name", "list.jsp"); //设置page节点的name属性
Element methodElement = document.createElement_x("method"); //设置method节点
methodElement.setTextContent("get"); //给method设置值
pageElement.appendChild(methodElement); //添加method节点到page节点内
Element displayElement = document.createElement_x("display"); //设置method节点
displayElement.setTextContent("list撒旦发放"); //给display设置值
pageElement.appendChild(displayElement); //添加display节点到page节点内
Element request_paramElement = document.createElement_x("request_param");
request_paramElement.setTextContent("request_param1|request_param2");
pageElement.appendChild(request_paramElement);
root.appendChild(pageElement);
pageElement = document.createElement_x("page"); //设置第二个page元素到
pageElement.setAttribute("name", "content.jsp"); //设置page节点的name属性
methodElement = document.createElement_x("method");
methodElement.setTextContent("post");
pageElement.appendChild(methodElement);
displayElement = document.createElement_x("display");
displayElement.setTextContent("content");
pageElement.appendChild(displayElement);
Element url_titleElement = document.createElement_x("url_title"); //设置url_title节点
url_titleElement.setTextContent("title,publisher,published_calendar"); //给url_title设置值
pageElement.appendChild(url_titleElement); //添加url_title节点到page节点内
root.appendChild(pageElement); //将page段加人根节点内
TransformerFactory transFactory = TransformerFactory.newInstance(); //开始把Document映射到文件
Transformer transFormer = transFactory.newTransformer();
DOMSource domSource = new DOMSource(document); //设置输出结果
File file = new File("MobileNetRule.xml"); //生成xml文件
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream out = new FileOutputStream(file); //文件输出流
StreamResult xmlResult = new StreamResult(out); //设置输入源
transFormer.transform(domSource, xmlResult); //输出xml文件
System.out.println(file.getAbsolutePath()); //测试文件输出的路径
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty("{/encoding/}","GB2312/");
ByteArrayOutputStream boc = new ByteArrayOutputStream();
t.transform(new DOMSource(document), new StreamResult(boc));
String xmlstring = boc.toString();
System.out.println(xmlstring);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args){
Test.generate();
}
}