Dom解析
//生成XML
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element element = document.createElement("books");
for (Product product : data) {
Element bookElement = document.createElement("book");
bookElement.setAttribute("id", product.getId());
Element nElement = document.createElement("name");
nElement.appendChild(document.createTextNode(product.getName()));
bookElement.appendChild(nElement);
Element aElement = document.createElement("author");
aElement.appendChild(document.createTextNode(product.getAuthor()));
bookElement.appendChild(aElement);
Element pElement = document.createElement("price");
pElement.appendChild(document.createTextNode(product.getPrice()));
bookElement.appendChild(pElement);
element.appendChild(bookElement);
}
document.appendChild(element);
//写入XML
TransformerFactory factory2 = TransformerFactory.newInstance();
Transformer transformer = factory2.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource xmlSource = new DOMSource(document);
FileOutputStream fos = openFileOutput("books.xml", MODE_PRIVATE);
StreamResult outputTarget = new StreamResult(fos);
transformer.transform(xmlSource, outputTarget);
fos.close();
//解析XML
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(openFileInput("books.xml"));
Element element = document.getDocumentElement();
NodeList tagName = element.getElementsByTagName("book");
for (int i = 0; i < tagName.getLength(); i++) {
Product product = new Product();
Element bookElement = (Element) tagName.item(i);
String id = bookElement.getAttribute("id");
product.setId(id);
Element nElement = (Element) bookElement.getElementsByTagName("name").item(0);
String name = nElement.getTextContent();
product.setName(name);
Element aElement = (Element) bookElement.getElementsByTagName("author").item(0);
String author = aElement.getTextContent();
product.setAuthor(author);
Element pElement = (Element) bookElement.getElementsByTagName("price").item(0);
String price = pElement.getTextContent();
product.setPrice(price);
data.add(product);
-----------------------------------------------------------------------------------------
SAX解析
//继承DefaultHandler
public class SaxHandler extends DefaultHandler {
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
data = new ArrayList<Root>();
areas = new ArrayList<Area>();
cities = new ArrayList<City>();
provinces = new ArrayList<Province>();
super.startDocument();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
super.startElement(uri, localName, qName, attributes);
tagName = qName;
if(tagName.equals("root")){
root = new Root();
provinces = new ArrayList<Province>();
root.setName(attributes.getValue(0));
}else if(tagName.equals("province")){
province = new Province();
cities = new ArrayList<City>();
province.setName(attributes.getValue(0));
province.setPostcode(attributes.getValue(1));
}else if(tagName.equals("city")){
city = new City();
areas = new ArrayList<Area>();
city.setName(attributes.getValue(0));
city.setPostcode(attributes.getValue(1));
}else if(tagName.equals("area")){
area = new Area();
area.setName(attributes.getValue(0));
area.setPostcode(attributes.getValue(1));
areas.add(area);
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
String text = new String(ch,start,length);
if(tagName.equals("name")&&!text.trim().equals("")){
languages.setName(text);
}else if(tagName.equals("ide")&&!text.trim().equals("")){
languages.setIde(text);
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
super.endElement(uri, localName, qName);
if(qName.equals("city")){
city.setArea(areas);
cities.add(city);
}else if(qName.equals("province")){
cities.add(city);
province.setCity(cities);
provinces.add(province);
}else if(qName.equals("root")){
root.setProvinces(provinces);
data.add(root);
}
}
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
super.endDocument();
}
//对外方法,返回解析内容
public ArrayList<Root> getRoots(){
return data;
}
-----------------------------------------------------------------------------------------
PULL解析
//生成
XmlSerializer serializer = Xml.newSerializer();
try {
serializer.setOutput(ops, "UTF-8");
serializer.startDocument("utf-8", true);
serializer.startTag(null, "root");
serializer.attribute(null, "classes", "1409f");
for (Person person : aList) {
serializer.startTag(null, "person");
serializer.startTag(null, "id");
serializer.text(person.getId());
serializer.endTag(null, "id");
serializer.startTag(null, "name");
serializer.text(person.getName());
serializer.endTag(null, "name");
serializer.startTag(null, "age");
serializer.text(person.getAge() + "");
serializer.endTag(null, "age");
serializer.startTag(null, "sex");
serializer.text(person.getSex());
serializer.endTag(null, "sex");
serializer.endTag(null, "person");
}
serializer.endTag(null, "root");
serializer.endDocument();
ops.flush();
ops.close();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//解析
public ArrayList<Person> getXML(InputStream inputStream) {
ArrayList<Person> aList = null;
Person person = null;
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(inputStream, "UTF-8");
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
aList = new ArrayList<Person>();
break;
case XmlPullParser.START_TAG:
if (parser.getName().equals("root")) {
String attributeValue = parser.getAttributeValue(0);
}
if (parser.getName().equals("person")){
person = new Person();
}
if (parser.getName().equals("id")) {
String id = parser.nextText();
person.setId(id);
}
if (parser.getName().equals("name")) {
String name = parser.nextText();
person.setName(name);
}
if (parser.getName().equals("age")) {
String age = parser.nextText();
System.out.println(age);
person.setAge(age);
}
if (parser.getName().equals("sex")) {
String sex = parser.nextText();
person.setSex(sex);
}
break;
case XmlPullParser.END_TAG:
if (parser.getName().equals("person")) {
aList.add(person);
}
break;
}
//循环条件
eventType = parser.next();
//生成XML
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element element = document.createElement("books");
for (Product product : data) {
Element bookElement = document.createElement("book");
bookElement.setAttribute("id", product.getId());
Element nElement = document.createElement("name");
nElement.appendChild(document.createTextNode(product.getName()));
bookElement.appendChild(nElement);
Element aElement = document.createElement("author");
aElement.appendChild(document.createTextNode(product.getAuthor()));
bookElement.appendChild(aElement);
Element pElement = document.createElement("price");
pElement.appendChild(document.createTextNode(product.getPrice()));
bookElement.appendChild(pElement);
element.appendChild(bookElement);
}
document.appendChild(element);
//写入XML
TransformerFactory factory2 = TransformerFactory.newInstance();
Transformer transformer = factory2.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource xmlSource = new DOMSource(document);
FileOutputStream fos = openFileOutput("books.xml", MODE_PRIVATE);
StreamResult outputTarget = new StreamResult(fos);
transformer.transform(xmlSource, outputTarget);
fos.close();
//解析XML
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(openFileInput("books.xml"));
Element element = document.getDocumentElement();
NodeList tagName = element.getElementsByTagName("book");
for (int i = 0; i < tagName.getLength(); i++) {
Product product = new Product();
Element bookElement = (Element) tagName.item(i);
String id = bookElement.getAttribute("id");
product.setId(id);
Element nElement = (Element) bookElement.getElementsByTagName("name").item(0);
String name = nElement.getTextContent();
product.setName(name);
Element aElement = (Element) bookElement.getElementsByTagName("author").item(0);
String author = aElement.getTextContent();
product.setAuthor(author);
Element pElement = (Element) bookElement.getElementsByTagName("price").item(0);
String price = pElement.getTextContent();
product.setPrice(price);
data.add(product);
-----------------------------------------------------------------------------------------
SAX解析
//继承DefaultHandler
public class SaxHandler extends DefaultHandler {
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
data = new ArrayList<Root>();
areas = new ArrayList<Area>();
cities = new ArrayList<City>();
provinces = new ArrayList<Province>();
super.startDocument();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
super.startElement(uri, localName, qName, attributes);
tagName = qName;
if(tagName.equals("root")){
root = new Root();
provinces = new ArrayList<Province>();
root.setName(attributes.getValue(0));
}else if(tagName.equals("province")){
province = new Province();
cities = new ArrayList<City>();
province.setName(attributes.getValue(0));
province.setPostcode(attributes.getValue(1));
}else if(tagName.equals("city")){
city = new City();
areas = new ArrayList<Area>();
city.setName(attributes.getValue(0));
city.setPostcode(attributes.getValue(1));
}else if(tagName.equals("area")){
area = new Area();
area.setName(attributes.getValue(0));
area.setPostcode(attributes.getValue(1));
areas.add(area);
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
String text = new String(ch,start,length);
if(tagName.equals("name")&&!text.trim().equals("")){
languages.setName(text);
}else if(tagName.equals("ide")&&!text.trim().equals("")){
languages.setIde(text);
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
super.endElement(uri, localName, qName);
if(qName.equals("city")){
city.setArea(areas);
cities.add(city);
}else if(qName.equals("province")){
cities.add(city);
province.setCity(cities);
provinces.add(province);
}else if(qName.equals("root")){
root.setProvinces(provinces);
data.add(root);
}
}
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
super.endDocument();
}
//对外方法,返回解析内容
public ArrayList<Root> getRoots(){
return data;
}
-----------------------------------------------------------------------------------------
PULL解析
//生成
XmlSerializer serializer = Xml.newSerializer();
try {
serializer.setOutput(ops, "UTF-8");
serializer.startDocument("utf-8", true);
serializer.startTag(null, "root");
serializer.attribute(null, "classes", "1409f");
for (Person person : aList) {
serializer.startTag(null, "person");
serializer.startTag(null, "id");
serializer.text(person.getId());
serializer.endTag(null, "id");
serializer.startTag(null, "name");
serializer.text(person.getName());
serializer.endTag(null, "name");
serializer.startTag(null, "age");
serializer.text(person.getAge() + "");
serializer.endTag(null, "age");
serializer.startTag(null, "sex");
serializer.text(person.getSex());
serializer.endTag(null, "sex");
serializer.endTag(null, "person");
}
serializer.endTag(null, "root");
serializer.endDocument();
ops.flush();
ops.close();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//解析
public ArrayList<Person> getXML(InputStream inputStream) {
ArrayList<Person> aList = null;
Person person = null;
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(inputStream, "UTF-8");
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
aList = new ArrayList<Person>();
break;
case XmlPullParser.START_TAG:
if (parser.getName().equals("root")) {
String attributeValue = parser.getAttributeValue(0);
}
if (parser.getName().equals("person")){
person = new Person();
}
if (parser.getName().equals("id")) {
String id = parser.nextText();
person.setId(id);
}
if (parser.getName().equals("name")) {
String name = parser.nextText();
person.setName(name);
}
if (parser.getName().equals("age")) {
String age = parser.nextText();
System.out.println(age);
person.setAge(age);
}
if (parser.getName().equals("sex")) {
String sex = parser.nextText();
person.setSex(sex);
}
break;
case XmlPullParser.END_TAG:
if (parser.getName().equals("person")) {
aList.add(person);
}
break;
}
//循环条件
eventType = parser.next();