1.加载xml文件获取document对象。
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;
}
2.解析xml
public static void xmlUpdateStrings(HashMap<String, Object> map,String path) {
Document document = load(path);
Node root = document.getDocumentElement();
if (root.hasChildNodes()) {
//获取跟节点下所有元素
NodeList ftpnodes = root.getChildNodes();
for (int i = 0; i < ftpnodes.getLength(); i++) {
Node nd = ftpnodes.item(i);
//判断加点元素名称和类型
if(nd!=null&&nd.getNodeType()!=nd.COMMENT_NODE&&nd.getNodeName()=="string"){
//获取节点下所有属性
NamedNodeMap aMap=nd.getAttributes();
//获取节点中名称为name属性对象
Node attr=aMap.getNamedItem("name");
//获取属性值
String app_name=attr.getNodeValue();
if(attr!=null&&"app_name".equals(app_name)){
//修改对应节点值
nd.getFirstChild().setNodeValue(map.get("app_name").toString()); //修改节点值
}
}
}
}
doc2XmlFile(document, path);
}
3.将document对象写入对应地址文件
public static boolean doc2XmlFile(Document document, String filename) {
boolean flag = true;
try {
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;
}
4.xml文件格式
<?xml version="1.0" encoding="utf-8" standalone="no"?><resources>
<string name="hello">Hello World, DHotelActivity!</string>
<string name="app_name">00000000000</string> (被修改的节点值)
<string name="more">更多</string>
<string name="nodata">暂无数据</string>
<string name="about">关于道有道</string>
<string name="toast_noresult">抱歉,未找到结果</string>
<string name="beijing">北京</string>
</resources>