android 下的xml解析、修改与保存的代码能发我一份吗?
发布网友
发布时间:2022-05-16 15:52
我来回答
共1个回答
热心网友
时间:2023-10-29 09:58
以下是我写的,仅供参考
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.Scanner;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
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.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.taiji.offlinedata.client.OfflineDataClient;
/**
* XML处理工具(w3c.Dom)
*
* @author 孙继成
*
*/
public class XMLUtil {
private static final String xmlEncoding = "GB2312";
/**
* 将XML文件以String的形式读取
*
* @param sysConfig
* 系统配置
* @param xmlFile
* 文件名
* @return
* @throws IOException
*/
public static String getXMLFile(String path, String xmlFile)
throws IOException {
String fileLocate = path + "/" + xmlFile;
return getXMLFile(fileLocate);
}
/**
* 将XML文件以String的形式读取
*
* @param fileLocate
* 文件全路径
* @return
* @throws IOException
*/
public static String getXMLFile(String fileLocate) throws IOException {
File file = new File(fileLocate);
if (file == null || !file.exists()) {
throw new FileNotFoundException("xml file not found in path '"
+ fileLocate + "'");
}
// Reader reader = new BufferedReader(new FileReader(file));
InputStream fileInputStream = new FileInputStream(file);
Scanner scan = new Scanner(fileInputStream);
StringBuffer sb = new StringBuffer();
while (scan.hasNext()) {
sb.append(scan.nextLine()).append("\n");
}
fileInputStream.close();
return sb.toString();
}
/**
* 读取XML文件,并返回文档
*
* @param filePath
* 文件位置
* @return
* @throws SAXException
* ,IOException
* @throws ParserConfigurationException
*/
public static Document getXmlFileASDocument(String filePath)
throws SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory docBuilderFactory = null;
DocumentBuilder docBuilder = null;
InputSource inputSource=null;
InputStream stream = null;
try {
stream = new FileInputStream(new File(filePath));
InputStreamReader streamReader = new InputStreamReader(stream,OfflineDataClient.XMLENCODEING);
inputSource = new InputSource(streamReader);
docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilder = docBuilderFactory.newDocumentBuilder();
return docBuilder.parse(inputSource);
} catch (SAXException e) {
throw e;
} catch (IOException e) {
throw e;
} finally {
docBuilder = null;
docBuilderFactory = null;
}
}
/**
* 用XML文本建立XML Document文档对象
*
* @param xml
* xml文本
* @return XML Document文档
* @throws ParserConfigurationException
* @throws DocumentException
*/
public static Document buildDocumentWithStr(String xml)
throws SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory docBuilderFactory = null;
DocumentBuilder docBuilder = null;
StringReader sr = null;
InputSource is = null;
try {
docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilder = docBuilderFactory.newDocumentBuilder();
sr = new StringReader(xml);
is = new InputSource(sr);
Document doc = docBuilder.parse(is);
return doc;
} catch (SAXException e) {
throw e;
} catch (IOException e) {
throw e;
} finally {
is = null;
sr.close();
docBuilder = null;
docBuilderFactory = null;
}
}
public static String getXMLStrWithDocument(Document xmlDocument)
throws Exception {
return getXMLStrWithDocument(xmlDocument.getDocumentElement());
}
public static String getXMLStrWithDocument(Element xmlElement)
throws Exception {
String format = XMLUtil.getXMLHeader();
StringBuffer sb = new StringBuffer();
sb.append(format);
convertElement2Str(xmlElement, sb, 0);
return sb.toString();
}
/**
* XML文件输出默认编码
*
* @return
*/
public static String getXMLHeader() {
return "<?xml version=\"1.0\" encoding=\"" + xmlEncoding + "\"?>\n";
}
/**
* XML文件输出指定编码
*
* @param encoding
* @return
*/
public static String getXMLHeader(String encoding) {
return "<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>\n";
}
/**
* 保存XML文档到指定文件
*
* @param xmlDocument
* @param xmlFile
* @throws IOException
*/
public static void saveDocument(Document xmlDocument, String xmlFile)
throws Exception {
try {
//String xml = getXMLStrWithDocument(xmlDocument);
//saveXML(xmlFile, xml);
TransformerFactory xformFactory
= TransformerFactory.newInstance();
Transformer idTransform = xformFactory.newTransformer();
idTransform.setOutputProperty(OutputKeys.ENCODING, OfflineDataClient.XMLENCODEING);
idTransform.setOutputProperty(OutputKeys.STANDALONE, "yes");
Source input = new DOMSource(xmlDocument);
Result output = new StreamResult(new FileOutputStream(xmlFile));
idTransform.transform(input, output);
} catch (Exception e) {
throw e;
}
}
/**
* 保存XML文本到指定文件
*
* @param filePathAndName
* 文件位置
* @param fileContent
* XML文本内容
* @throws IOException
*/
public static void saveXML(String filePathAndName, String fileContent)
throws IOException {
FileUtil.newTxtFile(filePathAndName, fileContent);
}
/**
* 将多个XML元素合并成一个Document,
*
* @param QName
* Document root
* @param elements
* 要合并的元素
* @throws ParserConfigurationException
*/
public static Document getDocument(String QName, Element[] elements) throws ParserConfigurationException {
DocumentBuilderFactory docBuilderFactory = null;
DocumentBuilder docBuilder = null;
Document doc = null;
try {
docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilder = docBuilderFactory.newDocumentBuilder();
doc = docBuilder.newDocument();
Element rootEle = doc.createElement(QName);
doc.appendChild(rootEle);
for (Element ele : elements) {
// if(ele.getParentNode() != null)
// ele.getParentNode().removeChild(ele);
rootEle.appendChild(copyElement(doc, ele, true));
}
return doc;
} catch (DOMException e) {
e.printStackTrace();
switch (e.code) {
case DOMException.DOMSTRING_SIZE_ERR:
MessageUtil.ERROR("DOMSTRING_SIZE_ERR");
break;
case DOMException.HIERARCHY_REQUEST_ERR:
MessageUtil.ERROR("HIERARCHY_REQUEST_ERR");
break;
case DOMException.INDEX_SIZE_ERR:
MessageUtil.ERROR("INDEX_SIZE_ERR");
break;
case DOMException.INUSE_ATTRIBUTE_ERR:
MessageUtil.ERROR("INUSE_ATTRIBUTE_ERR");
break;
case DOMException.INVALID_ACCESS_ERR:
MessageUtil.ERROR("INVALID_ACCESS_ERR");
break;
case DOMException.INVALID_CHARACTER_ERR:
MessageUtil.ERROR("INVALID_CHARACTER_ERR");
break;
case DOMException.INVALID_MODIFICATION_ERR:
MessageUtil.ERROR("INVALID_MODIFICATION_ERR");
break;
case DOMException.INVALID_STATE_ERR:
MessageUtil.ERROR("INVALID_STATE_ERR");
break;
case DOMException.NAMESPACE_ERR:
MessageUtil.ERROR("NAMESPACE_ERR");
break;
case DOMException.NO_DATA_ALLOWED_ERR:
MessageUtil.ERROR("NO_DATA_ALLOWED_ERR");
break;
case DOMException.NO_MODIFICATION_ALLOWED_ERR:
MessageUtil.ERROR("NO_MODIFICATION_ALLOWED_ERR");
break;
case DOMException.NOT_FOUND_ERR:
MessageUtil.ERROR("NOT_FOUND_ERR");
break;
case DOMException.NOT_SUPPORTED_ERR:
MessageUtil.ERROR("NOT_SUPPORTED_ERR");
break;
case DOMException.SYNTAX_ERR:
MessageUtil.ERROR("SYNTAX_ERR");
break;
case DOMException.WRONG_DOCUMENT_ERR:
MessageUtil.ERROR("WRONG_DOCUMENT_ERR");
break;
default:
MessageUtil.ERROR("Unknown DOM exception");
break;
}
throw e;
} finally {
docBuilder = null;
docBuilderFactory = null;
}
}
private static Element copyElement(Document doc, Element e, boolean deep) {
NodeList nl = e.getChildNodes();
// node name and attrs
Element newElement = doc.createElement(e.getNodeName());
NamedNodeMap attrs = e.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Node n = attrs.item(i);
newElement.setAttribute(n.getNodeName(), n.getNodeValue());
}
for (int i = 0; i < nl.getLength(); i++) {
//System.out.println("Node type" + nl.item(i).getNodeType());
if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
if(!deep) break;
newElement.appendChild(copyElement(doc, (Element)nl.item(i), deep));
} else {
String value = nl.item(i).getNodeValue().trim();
if (value.length() > 0) {
switch (nl.item(i).getNodeType()) {
case Node.CDATA_SECTION_NODE:
newElement.appendChild(doc.createCDATASection(value));
break;
case Node.COMMENT_NODE:
newElement.appendChild(doc.createComment(value));
break;
case Node.TEXT_NODE:
newElement.appendChild(doc.createTextNode(value));
break;
default:
newElement.appendChild(doc.createTextNode(value));
break;
}
}
}
}
return newElement;
}
public static void convertElement2Str(Element e, StringBuffer sb, int intTab) {
if(e == null) return;
NodeList nl = e.getChildNodes();
sb.append(appendTab(intTab));
// node name and attrs
sb.append("<" + e.getNodeName() + getDocumentAttrs(e) + ">");
for (int i = 0; i < nl.getLength(); i++) {
//System.out.println("Node type" + nl.item(i).getNodeType());
if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
sb.append("\n");
convertElement2Str((Element) nl.item(i), sb, intTab + 1);
sb.append(appendTab(intTab));
} else {
String value = nl.item(i).getNodeValue().trim();
if (value.length() > 0) {
switch (nl.item(i).getNodeType()) {
case Node.CDATA_SECTION_NODE:
sb.append("\n").append(appendTab(intTab + 1));
sb.append("<![CDATA[").append(value).append("]]> \n");
break;
case Node.COMMENT_NODE:
sb.append("\n").append(appendTab(intTab + 1));
sb.append("<!-- ").append(value).append(" --> \n");
break;
case Node.TEXT_NODE:
sb.append(value);
break;
default:
sb.append(value);
break;
}
}
}
}
sb.append("</" + e.getNodeName() + ">\n");
}
private static String getDocumentAttrs(Element e) {
String s = "";
NamedNodeMap attrs = e.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Node n = attrs.item(i);
s += " " + n.getNodeName() + "='" + n.getNodeValue() + "'";
}
return s;
}
private static String appendTab(int intTab) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < intTab; i++) {
sb.append("\t");
}
return sb.toString();
}
}