当前位置: 编程技术>java/j2ee
java对XML文件的解析、节点的增加、删除操作总结
来源: 互联网 发布时间:2014-10-18
本文导语: 1、java代码: 主要采用dom来进行操作 代码如下: package test; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; impor...
1、java代码:
主要采用dom来进行操作
package test;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
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
主要采用dom来进行操作
代码如下:
package test;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
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