xml格式,一种常用的数据格式,可以存放各种信息。比如城市名。
DOM方法解析:
xml 的读取。( xml文件存放在assets中。)
try {
InputStream is =getResources().getAssets().open("strings.xml");
DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(is);
Element element =document.getDocumentElement();
NodeList list =element.getElementsByTagName("string");
for (int i = 0; i < list.getLength(); i++) {
Element string = (Element) list.item(i);
tv.append(string.getAttribute("name"));
tv.append(string.getElementsByTagName("lb").item(0).getTextContent());
}
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
try {
DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document newxmlDocument = builder.newDocument();
Element languages = newxmlDocument.createElement("languages");
languages.setAttribute("category", "IT");
Element lan1 = newxmlDocument.createElement("lan");
lan1.setAttribute("id", "1");
Element name1 = newxmlDocument.createElement("name");
name1.setTextContent("java");
Element ide1 = newxmlDocument.createElement("ide");
ide1.setTextContent("eclipse");
lan1.appendChild(name1);
lan1.appendChild(ide1);
languages.appendChild(lan1);
Element lan2 = newxmlDocument.createElement("lan");
lan2.setAttribute("id", "2");
Element name2 = newxmlDocument.createElement("name");
name2.setTextContent("swift");
Element ide2 = newxmlDocument.createElement("ide");
ide2.setTextContent("xcode");
lan2.appendChild(name1);
lan2.appendChild(ide1);
languages.appendChild(lan2);
newxmlDocument.appendChild(languages);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty("encoding", "utf-8");
StringWriter sWriter =new StringWriter();
transformer.transform(new DOMSource(newxmlDocument), new StreamResult(sWriter));
tv.setText(sWriter.toString());
} catch (DOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}