JAVA操作XML实例分析
程序员文章站
2024-03-02 08:31:46
本文实例讲述了java操作xml的方法。分享给大家供大家参考。具体如下:
java代码如下:
复制代码 代码如下:import java.io.file;
impor...
本文实例讲述了java操作xml的方法。分享给大家供大家参考。具体如下:
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=(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[price<10]", root);
system.out.println("--- 再将所有价格低于10的书删除 ---");
system.out.println("--- 符合条件的书有 "+somebooks.getlength()+"本。 ---");
for(int i=0;i<somebooks.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();
}
}
}
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[price<10]", root);
system.out.println("--- 再将所有价格低于10的书删除 ---");
system.out.println("--- 符合条件的书有 "+somebooks.getlength()+"本。 ---");
for(int i=0;i<somebooks.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>
<price>10</price>
<memo>这是一本很好看的书。</memo>
</book>
<book id="b02">
<name>三国演义</name>
<price>10</price>
<memo>四大名著之一。</memo>
</book>
<book id="b03">
<name>水浒</name>
<price>6</price>
<memo>四大名著之一。</memo>
</book>
<book id="b04">
<name>红楼</name>
<price>5</price>
<memo>四大名著之一。</memo>
</book>
</books>
<books>
<book>
<name>哈里波特</name>
<price>10</price>
<memo>这是一本很好看的书。</memo>
</book>
<book id="b02">
<name>三国演义</name>
<price>10</price>
<memo>四大名著之一。</memo>
</book>
<book id="b03">
<name>水浒</name>
<price>6</price>
<memo>四大名著之一。</memo>
</book>
<book id="b04">
<name>红楼</name>
<price>5</price>
<memo>四大名著之一。</memo>
</book>
</books>
希望本文所述对大家的java程序设计有所帮助。