Java操作xml文件

时间:2023-03-10 01:41:53
Java操作xml文件

Bbsxml.java

public class Bbsxml {
private String imgsrc;
private String title;
private String url; public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getImgsrc() {
return imgsrc;
}
public void setImgString imgsrc) { < /span>
this.imgsrc = imgsrc;
} public static void main(String[] args) {
// TODO Auto-generated method stub } }

XmlOprate.java

public class XmlOprate {
Document doc;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
NodeList imags;
String path; public NodeList getImags() {
return imags;
} public void setImags(NodeList imags) {
this.imags = imags;
} /**
* 构造方法
*
* @param path
* :xml文件的路径
* @param nodes
* :要解析的xml节点名称
*/
public XmlOprate(String path) {
super();
this.path = path;
// System.out.println(System.getProperty("user.dir"));
} /**
* 解析XML
*
* @param path
*/
public void readXml() {
try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse(path);
doc.normalize(); NodeList imags = doc.getElementsByTagName("imags");
this.setImags(imags);
for (int i = 0; i < imags.getLength(); i++) {
Element link = (Element) imags.item(i);
System.out.print("imgsrc=\'#\'" /span>);
System.out.println(link.getElementsByTagName("imgsrc").item(0)
.getFirstChild().getNodeValue());
System.out.print("title: ");
System.out.println(link.getElementsByTagName("title").item(0)
.getFirstChild().getNodeValue());
System.out.print("url: ");
System.out.println(link.getElementsByTagName("url").item(0)
.getFirstChild().getNodeValue());
System.out.println();
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} } /**
* http://www.ablanxue.com 解析XML,返回List集合,Bbsxm
* 只是一个普通的javabean,只提供get,set的方法l,在此不写出,可自己创建了
*
* @param path
*/ public List<Bbsxml> xml() {
List<Bbsxml> list = null;
list = new ArrayList<Bbsxml>();
try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse(path);
doc.normalize();
Bbsxml bbsxml = null;
NodeList imags = doc.getElementsByTagName("imags");
this.setImags(imags);
for (int i = imags.getLength() - 1; i > -1; i--) {
Element link = (Element) imags.item(i); bbsxml = new Bbsxml();
bbsxml.setImglink.getElementsByTagName("imgsrc").item(0)
.getFirstChild().getNodeValue());
bbsxml.setTitle(link.getElementsByTagName("title").item(0)
.getFirstChild().getNodeValue());
bbsxml.setUrl(link.getElementsByTagName("url").item(0)
.getFirstChild().getNodeValue());
list.add(bbsxml); }
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} return list;
} /**
* addCode
*
* @param path
*/
public void addXmlCode(String imgsrc, String title, String url) { try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse(path);
doc.normalize(); Text textseg;
Element imag = doc.createElement("imags"); Element linkimgsrc = doc.createElement("imgsrc");
textseg = doc.createTextNode(imgsrc);
linkimgsrc.appendChild(textseg);
imag.appendChild(linkimgsrc); Element linktitle = doc.createElement("title");
textseg = doc.createTextNode(title);
linktitle.appendChild(textseg);
imag.appendChild(linktitle); Element linkurl = doc.createElement("url");
textseg = doc.createTextNode(url);
linkurl.appendChild(textseg);
imag.appendChild(linkurl); doc.getDocumentElement().appendChild(imag); TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer; transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new java.io.File(path));
transformer.transform(source, result);
} catch (Exception e) { }
} /**
* delete xml code
*
* @param path
*/
public void delXmlCode() { try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
doc = builder.parse(path);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
doc.normalize();
NodeList imags = doc.getElementsByTagName("imags"); // if (imags.getLength() > 9) {
// 删除节点
Element elink = (Element) imags.item(0);
elink.removeChild(elink.getElementsByTagName("imgsrc").item(0));
elink.removeChild(elink.getElementsByTagName("title").item(0));
elink.removeChild(elink.getElementsByTagName("url").item(0)); doc.getFirstChild().removeChild(elink); TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = null;
try {
transformer = tFactory.newTransformer();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new java.io.File(path));
try {
transformer.transform(source, result);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// } } public static void main(String[] args) {
XmlOprate xm = new XmlOprate("data.xml");
// xm.readXml();
// xm.addXmlCode("images/1.gif", "xuexiii", "http://www.baidu.com");
xm.delXmlCode();
} }

  

data.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<imags>
<imgsrc>images/ad-02.jpg</imgsrc>
<title>java读取xml文件</title>
<url>http://www.ablanxue.com</url>
</imags>
<imags>
<imgsrc>images/1.gif</imgsrc>
<title>xuexiii</title>
<url>http://www.baidu.com</url>
</imags>
</root>

JSP页面直接操作 xml.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="javax.xml.parsers.*"%>
<%@ page import="org.w3c.dom.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<%
//建立一个解析器工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//获得一个具体的解析器对象
DocumentBuilder builder = factory.newDocumentBuilder();
//对XML文档进行解析,获得Document对象
Document doc = builder.parse(request.getRealPath("/")+ "WEB-INF/data.xml");
doc.normalize();
//获取所有的book元素列表
NodeList books = doc.getElementsByTagName("book");
%>
</head>
<body>
<h2>图书列表</h2>
<br>
<%
for (int i = 0; i < books.getLength(); i++) {
//获取一个book元素
Element book = (Element) books.item(i);
//以下获取book的子元素,并输出
out.print("title:");
out.println(book.getElementsByTagName("title").item(0).getFirstChild().getNodeValue());
out.print("<br>");
out.print("URL:");
out.println(book.getElementsByTagName("url").item(0).getFirstChild().getNodeValue());
out.print("<br>");
out.print("Author:");
out.println(book.getElementsByTagName("author").item(0).getFirstChild().getNodeValue());
out.print("<br>");
out.print("Date:");
Element bookdate = (Element) book.getElementsByTagName("date").item(0);
String day = book.getElementsByTagName("day").item(0).getFirstChild().getNodeValue();
String month = book.getElementsByTagName("month").item(0).getFirstChild().getNodeValue();
String year = book.getElementsByTagName("year").item(0).getFirstChild().getNodeValue();
out.println(day + "-" + month + "-" + year);
out.print("<br>");
out.print("Description:");
out.println(book.getElementsByTagName("description").item(0).getFirstChild().getNodeValue());
out.print("<br><br>");
}
%>
</body>
</html>