//创建DocumentBuilderFactory对象
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
try {
//创建DocumentBuilder对象
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
//通过DocumentBuilder对象的parse方法返回一个Document对象
InputStream is = null;
File file = new File(XmlConstants.CONFIG_XML_PATH);
if (!file.exists()) {
is = context.getResources().openRawResource(R.raw.local_config_info);
} else {
is = new FileInputStream(file);
}
Document document = documentBuilder.parse(is);
try {
NodeList nodeList = document.getElementsByTagName("tag");
if (nodeList.getLength() > 0) {
Node node = nodeList.item(0);
node.setTextContent("node content");
}
} catch (Exception e) {
e.printStackTrace();
}
try {
Element element = (Element) document.getElementsByTagName("tag2").item(0);
element.setAttribute("attributeName", "attributeValue");
} catch (Exception e) {
e.printStackTrace();
}
OutputStream os = null;
try {
//将内存中的Dom保存到文件
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
//设置输出的xml的格式,utf-8
transformer.setOutputProperty(OutputKeys.ENCODING, CommonConstants.ENCODE_UTF8);
transformer.setOutputProperty(OutputKeys.VERSION, doc.getXmlVersion());
// 设置换行
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//设置缩进量
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
// 是否忽略XML声明
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
DOMSource source = new DOMSource(doc);
//打开输出流
File file = new File("//file_path");
if (!file.exists()) {
file.createNewFile();
}
os = new FileOutputStream(file);
//xml的存放位置
StreamResult src = new StreamResult(os);
transformer.transform(source, src);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (null != os) {
os.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}