XML文档的生成和解析操作方法

XML文档和JSon文档同为网络传输中的数据格式,JSon的解析和创建已经在新浪微博的使用中相当熟悉,故仅仅记载XML文档的相关方法。

关于XML文档:

1.一种便于编辑和传输的数据文件格式

2.xml文件中的数据保存方式为:根元素>>>子元素>>>子元素的子元素内容

具体代码:

//解析方法
DocumentBiudlerFactory builderFactory = DocumentBiudlerFactory.newInstance();
DocumentBiudler builder = biudlerFactory.newDocumentBuilder();
Document document = builder.parese(getAssets().open("XXXX.xml"));
Element element = document.getDocumentElement();
NodeList list = element.getElementByTagName("subTitle");
for(int i=0;i<list.getLength();i++){
Element subTitle = (Element) list.item(i);
text.append(subTitle.getAttribute("id")+"\n");
text.append(subTitle.getAttribute("name").item(0)+"\n");
}
DocumentBiudlerFactory builderFactory = DocumentBiudlerFactory.newInstance();

DocumentBiudler builder = biudlerFactory.newDocumentBuilder();
Document newxml = builder.newDocument(); Element mainTitle = newxml.createElement("mainTitle");
mainTitle.setAttribute("KEY","values"); Element subTitle1 = newxml.createElement("subTitle1");
subTitle.setAttribute("id","1");
Element name1 = newxml.createElement("name1");
name1.setTextContent("name1");
subTitle1.appendChild(name1);
mainTitle.append(subTitle1); newxml.appendChild(mainTitle); TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty("encoding","utf-8");
StringWriter sw = new StringWriter();
transformer.transform(new DOMSource(newxml),new StreamResult(sw)); text.setText(sw.toSring()); //由于纯手打代码,有很多异常没有被捕获
上一篇:Java之byte、char和String类型相互转换


下一篇:XMLHelper类 源码(XML文档帮助类,静态方法,实现对XML文档的创建,及节点和属性的增、删、改、查)