Skip to content

Instantly share code, notes, and snippets.

@dzwillpower
Created September 26, 2012 11:43
Show Gist options
  • Save dzwillpower/3787540 to your computer and use it in GitHub Desktop.
Save dzwillpower/3787540 to your computer and use it in GitHub Desktop.
xml解析 dom 解析
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="12">
<name>thinking in java</name>
<price>85.5</price>
</book>
<book id="15">
<name>android 疯狂的讲义</name>
<price>125</price>
</book>
</books>
package com.example.xmlparse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class DomXmlParse extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonDomParse = (Button) findViewById(R.id.btnDomParse);
buttonDomParse.setOnClickListener(new domParseListener());
}
public class domParseListener implements OnClickListener {
@Override
public void onClick(View v) {
InputStream inputstream = DomXmlParse.class.getClassLoader()
.getResourceAsStream("book.xml");
try {
List<Book> list = getBooks(inputstream);
for (Book book : list) {
System.out.println(book.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public List<Book> getBooks(InputStream inputstream) throws Exception {
List<Book> list = new ArrayList<Book>();
// 创建一个documemt解析的工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(inputstream);
Element element = document.getDocumentElement();// 获得元素的节点
NodeList bookNodes = element.getElementsByTagName("book");
for (int i = 0; i < bookNodes.getLength(); i++) {
Element bookElement = (Element) bookNodes.item(i);
Book book = new Book();
book.setId(Integer.parseInt(bookElement.getAttribute("id")));
NodeList childNodes = bookElement.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE) {
if ("name".equals(childNodes.item(j).getNodeName())) {
book.setName(childNodes.item(j).getFirstChild()
.getNodeValue());
} else if ("price".equals(childNodes.item(j).getNodeName())) {
book.setPrice(Float.parseFloat(childNodes.item(j)
.getFirstChild().getNodeValue()));
}
}
}
list.add(book);
}
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment