java xml操作

把 DOM element 转为 String

public String nodeToString(Node node) throws Exception{
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
StringWriter sw = new StringWriter();
trans.transform(new DOMSource(node), new StreamResult(sw));
String s = sw.toString();
return s;
}

String转Document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse( new ByteArrayInputStream(str.getBytes()));
//或 Document doc = builder.parse( new java.io.StringReader(str));


xml更新
xml:
<?xml version="1.0" encoding="UTF-8"?>
<users>
<Messages>
<sendName>sendUsers</sendName>
<receiveName>snake</receiveName>
<date>2007-12-04 12:20:00</date>
<status>0</status>
<message>this is Content</message>
</Messages>
</users>


import java.io.File;
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.Node;
import org.w3c.dom.NodeList;

public class JavaXML {
public static boolean doc2XmlFile(Document document, String filename) {
boolean flag = true;
try {
/** 将document中的内容写入文件中 */
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
/** 编码 */
// transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File(filename));
transformer.transform(source, result);
} catch (Exception ex) {
flag = false;
ex.printStackTrace();
}
return flag;
}

public static Document load(String filename) {
Document document = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(new File(filename));
document.normalize();
} catch (Exception ex) {
ex.printStackTrace();
}
return document;
}

/**
* 演示修改文件的具体某个节点的值
*/
public static void xmlUpdateDemo() {
Document document = load("message.xml");
Node root = document.getDocumentElement();
/** 如果root有子元素 */
if (root.hasChildNodes()) {
/** ftpnodes */
NodeList ftpnodes = root.getChildNodes();
/** 循环取得ftp所有节点 */
for (int i = 0; i < ftpnodes.getLength(); i++) {
NodeList ftplist = ftpnodes.item(i).getChildNodes();
for (int k = 0; k < ftplist.getLength(); k++) {
Node subnode = ftplist.item(k);
if (subnode.getNodeType() == Node.ELEMENT_NODE
&& subnode.getNodeName() == "status") {
subnode.getFirstChild().setNodeValue("1");
}
}

}
}

doc2XmlFile(document, "message.xml");
}

public static void main(String args[]) throws Exception {
JavaXML.xmlUpdateDemo();
}
}

XPATH 更新节点值
// 创建 XpathExpression 对象
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();
XPathExpression xPathExpression = xPath.compile("/users/Messages/sendName[@date='090915']/firstName");
// 结合 XML 文件和 XPATH 的表达式就可以得到相关节点的内容
Node firstName = (Node)xPathExpression.evaluate(doc,XPathConstants.NODE);
firstName.getFirstChild().setNodeValue("zeng");
System.out.println(nodeToString(doc));
//xPathExpression = xPathTest.compile("ancestor::Messages");
//当前结点的Messages祖先结点
// Node n = (Node)xPathExpression.evaluate(firstName,XPathConstants.NODE);
// System.out.println(nodeToString(doc));


一个可以完成读取、打印输出、保存xml等等功能的java

import java.util.*;
import java.net.URL;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.Serializer;
import org.apache.xml.serialize.SerializerFactory;
import org.apache.xml.serialize.XMLSerializer;
import org.xml.sax.InputSource;

public class xmlUtil implements java.io.Serializable {

public xmlUtil()
{
}
public static DocumentBuilder getBuilder() throws ParserConfigurationException
{
DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
return builder;
}
//get a document from given file
public static Document getDocument(String path) throws Exception
{
//BufferedReader fileIn=new BufferedReader(new FileReader(path));
File f = new File(path);
DocumentBuilder builder=getBuilder();
Document doc = builder.parse(f);
return doc;
}
//get a document from InputStream
public static Document getDocument(InputStream in) throws Exception
{
DocumentBuilder builder=getBuilder();
Document doc = builder.parse(in);
return doc;
}

//create a empty document
public static Document getNewDoc() throws Exception
{
DocumentBuilder builder=getBuilder();
Document doc = builder.newDocument();
return doc;
}
//create a document from given string
public static Document getNewDoc(String xmlStr)
{
Document doc = null;
try
{
StringReader sr = new StringReader(xmlStr);
InputSource iSrc = new InputSource(sr);
DocumentBuilder builder=getBuilder();
doc = builder.parse(iSrc);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return doc;
}

//save a document as a file at the given file path
public static void save(Document doc, String filePath)
{
try
{
OutputFormat format = new OutputFormat(doc); //Serialize DOM
format.setEncoding("GB2312");
StringWriter stringOut = new StringWriter(); //Writer will be a String
XMLSerializer serial = new XMLSerializer(stringOut, format);
serial.asDOMSerializer(); // As a DOM Serializer
serial.serialize(doc.getDocumentElement());
String STRXML = stringOut.toString(); //Spit out DOM as a String
String path = filePath;
writeXml(STRXML, path);

}
catch (Exception e)
{
e.printStackTrace();
}
}

//save a string(xml) in the given file path
public static void writeXml(String STRXML, String path)
{
try
{
File f = new File(path);
PrintWriter out = new PrintWriter(new FileWriter(f));
out.print(STRXML + "\n");
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
//format a document to string
public static String toString(Document doc)
{
String STRXML = null;
try
{
OutputFormat format = new OutputFormat(doc); //Serialize DOM
format.setEncoding("GB2312");
StringWriter stringOut = new StringWriter(); //Writer will be a String
XMLSerializer serial = new XMLSerializer(stringOut, format);
serial.asDOMSerializer(); // As a DOM Serializer
serial.serialize(doc.getDocumentElement());
STRXML = stringOut.toString(); //Spit out DOM as a String
}
catch (Exception e)
{
e.printStackTrace();
}
return STRXML;
}
//format a node to string
public static String toString(Node node, Document doc)
{
String STRXML = null;
try
{
OutputFormat format = new OutputFormat(doc); //Serialize DOM
format.setEncoding("GB2312");
StringWriter stringOut = new StringWriter(); //Writer will be a String
XMLSerializer serial = new XMLSerializer(stringOut, format);
serial.asDOMSerializer(); // As a DOM Serializer
serial.serialize((Element) node);
STRXML = stringOut.toString(); //Spit out DOM as a String
}
catch (Exception e)
{
e.printStackTrace();
}
return STRXML;
}

public static void main(String[] args) throws Exception
{
String pathRoot = "NeTrees.xml";
Document doc,doc1;
try
{
doc = xmlUtil.getDocument(pathRoot);
doc1 = xmlUtil.getDocument(pathRoot);
if(doc == doc1)
{
System.out.println("They are same objects!");
}
else
{
System.out.println("They are different!");
OutputFormat format = new OutputFormat(doc); //Serialize DOM
format.setEncoding("GB2312");
StringWriter stringOut = new StringWriter(); //Writer will be a String
XMLSerializer serial = new XMLSerializer(stringOut, format);
serial.asDOMSerializer(); // As a DOM Serializer
serial.serialize(doc.getDocumentElement());
String STRXML = stringOut.toString(); //Spit out DOM as a String
System.out.println(STRXML);
}
}
catch (Exception ex)
{
System.out.print("Reading file\"" + pathRoot + "\" error!");
ex.printStackTrace();
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值