新网创想网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
public class XMLBuilder { public static String buildXML(PlayerCount player) {
梓潼网站制作公司哪家好,找创新互联公司!从网页设计、网站建设、微信开发、APP开发、响应式网站等网站项目制作,到程序开发,运营维护。创新互联公司成立于2013年到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联公司。
StringBuilder builder = new StringBuilder();
builder.append("root");
builder.append("server").append(player.getServerName()).append("/server");
builder.append("player_count").append(player.getPlayerCount()).append("/player_count");
builder.append("/root");
return builder.toString();
}
}
这是一个用JAVA W3C DOM 进行XML操作的例子,包含了查询、增加、修改、删除、保存的基本操作。较完整的描述了一个XML的整个操作流程。适合刚入门JAVA XML操作的朋友参考和学习。
假设有XML文件:test1.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
下面是为Test.java
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=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);
//--- 新建一本书完成 ----
//--- 下面对《哈里波特》做一些修改。 ----
//--- 查询找《哈里波特》----
theBook=(Element) selectSingleNode("/books/book[name='哈里波特']", root);
System.out.println("--- 查询找《哈里波特》 ----");
output(theBook);
//--- 此时修改这本书的价格 -----
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();
}
}
}
StringBuffer results = new StringBuffer();
results.append("topBeans");
arriylist1 = searchTop.finddepartment(shiyebu_id);
for (TopBean topBean : arriylist1)
{
results.append("department");
results.append("departmentId");
results.append(topBean.getDepartmentId());
results.append("/departmentId");
results.append("departmentName");
results.append(topBean.getDepartmentName());
results.append("/departmentName");
results.append("/department");
}
results.append("/topBeans");
Response.setContentType("text/xml");
Response.setHeader("Cache-Control", "no-cache");
Response.setCharacterEncoding("UTF-8");
PrintWriter pw;
pw = Response.getWriter();
pw.write(results.toString());
pw.flush();
下面提供了XML解析成实体类,以及实体类转换成xml的方法。
public class SwitchXML {
private XStream xStream = new XStream();
private String xmlPath = "D:/data.xml";
// 1. obj - xml(object类型转换为xml类型)
public String printXML(User user) {
System.out.println("obj - xml");
String xml = xStream.toXML(user);
System.out.println(xml);
return xml;
}
// 2. xml-obj(xml类型转换为object类型,并打印)
public void printObj(String xml) {
System.out.println("xml - obj");
User u = (User) xStream.fromXML(xml);
System.out.println(u.getUserName() + " " + u.getPassWord() + " " + u.getRegisteredTime());
}
// 3. 将object类型转换为xml类型,并写入XML文件(其他格式也可以,比如txt文件)
public void writerXML(User user) {
try {
FileOutputStream fs = new FileOutputStream(xmlPath);
xStream.toXML(user, fs);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
// 4. 读取XML文件,加载进相应Object类型
public void readerXML() {
User user = new User();
FileInputStream fis = null;
try {
fis = new FileInputStream(xmlPath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
xStream.fromXML(fis, user);
// 打印对象信息
System.out.println(user.toString());
// 打印对象的属性值
System.out.println(user.getUserName() + "-" + user.getPassWord() + "-"
+ user.getRegisteredTime());
}
public static void main(String[] args) {
// 用户名
String username = "admin";
// 密码
String password = "admin";
// 注册时间
Date now = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
String registeredtime = format.format(now);
User user = new User(username, password, registeredtime);
SwitchXML switchXML = new SwitchXML();
// 1. object类型转换为xml类型,在控制台打印
String xml = switchXML.printXML(user);
System.out.println("---------------------");
// 2. xml类型转换为object类型,在控制台打印
switchXML.printObj(xml);
System.out.println("---------------------");
// 3. 将object类型转换为xml类型,并写入XML文件
switchXML.writerXML(user);
System.out.println("---------------------");
// 4. 读取XML文件,加载进相应Object类型
switchXML.readerXML();
}