我正在尝试使用 DOM 和 PullParser 读取和写入 XML 文件。我从这个链接http://www.phonesdevelopers.com/1707053/启发了这段代码的一部分。这是主要活动:
public class MainActivity extends Activity implements OnClickListener {
Button button;
ListView listView;
List<Classe> classes = null;
// XML node names
static final String NODE_CL = "tns:classe";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsById();
try {
testClasse() ;
testSave();
} catch (Exception e) {
e.printStackTrace();
}
button.setOnClickListener(this);
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
listView = (ListView) findViewById(R.id.employeeList);
}
@Override
public void onClick(View v) {
XMLDOMParser parser = new XMLDOMParser();
File file = new File("data/data/com/theopentutorials/android/xy.xml");
InputStream is;
try {
is = new FileInputStream(file.getPath());
Document doc = parser.getDocument(is);
// Get elements by name employee
NodeList nodeList = doc.getElementsByTagName(NODE_CL);
classes = new ArrayList<Classe>();
/*
* for each <employee> element get text of name, department, type
* and email and line1, city, state, zipcode of <address> element.
*/
for (int i = 0; i < nodeList.getLength(); i++) {
Element c = (Element) nodeList.item(i);
Classe classe = new Classe();
classe.setName(c.getAttribute("namecls"));
classes.add(classe);
}
displayOutput();
} catch (IOException e1) {
e1.printStackTrace();
}
}
private void displayOutput() {
ArrayAdapter<Classe> adapter = new ArrayAdapter<Classe>(this,R.layout.list_item,classes);
listView.setAdapter(adapter);
}
public void testClasse() throws Exception
{
ClasseService ps = new ClasseService();
InputStream xml = this.getClass().getClassLoader().getResourceAsStream("Classe.xml");
List<Classe> lst = ps.getPeople(xml);
}
public void testSave() throws Exception
{
ClasseService ps = new ClasseService();
List<Classe> lst = new ArrayList<Classe>();
lst.add(new Classe("XY0001"));
lst.add(new Classe("0002"));
File xmlFile = new File(this.getBaseContext().getFilesDir(), "xy.xml"); // data/data/package name/files
OutputStream os = new FileOutputStream(xmlFile);
ps.saveDataToXML(os, lst);
}
}
这是 XML 解析器
public class XMLDOMParser {
//Returns the entire XML document
public static Document getDocument(InputStream inputStream) {
Document document = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inputSource = new InputSource(inputStream);
document = db.parse(inputSource);
document.getDocumentElement().normalize();
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return document;
}
/*
* I take a XML element and the tag name, look for the tag and get
* the text content i.e for <employee><name>Kumar</name></employee>
* XML snippet if the Element points to employee node and tagName
* is name I will return Kumar. Calls the private method
* getTextNodeValue(node) which returns the text value, say in our
* example Kumar. */
public String getValue(Element item, String name) {
NodeList nodes = item.getElementsByTagName(name);
return this.getTextNodeValue(nodes.item(0));
}
private final String getTextNodeValue(Node node) {
Node child;
if (node != null) {
if (node.hasChildNodes()) {
child = node.getFirstChild();
while(child != null) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
child = child.getNextSibling();
}
}
}
return "";
}
}
我们在其中进行写作的 ClasseService 类
public class ClasseService
{
/**
* XML
*
* @param xml XML
*/
public List<Classe> getPeople(InputStream xml) throws Exception
{
List<Classe> lst = null;
com.theopentutorials.android.beans.Classe classe = null;
// ANDROIDAPIpull
XmlPullParser pullParser = Xml.newPullParser();
// XML
pullParser.setInput(xml, "UTF-8");
//
int event = pullParser.getEventType();
//
while (event != XmlPullParser.END_DOCUMENT) //
{ String nodeName = pullParser.getName();
switch (event)
{
case XmlPullParser.START_DOCUMENT: //
lst = new ArrayList<Classe>();
break;
case XmlPullParser.START_TAG: //
if ("tns:classe".equals(nodeName))
{
String id = pullParser.getAttributeValue(0);
classe = new Classe();
classe.setName(id);
}
break;
}
}
return lst;
}
/**
* XML
*
* @param os
* @param Classe
* @throws Exception
*/
public void saveDataToXML(OutputStream os, List<Classe> lst) throws Exception
{
XmlSerializer xs = Xml.newSerializer();
xs.setOutput(os, "UTF-8");
xs.startDocument("UTF-8", true);
xs.startTag(null, "tns:Classes");
for (Classe p : lst)
{
xs.startTag(null, "tns:classe");
xs.attribute(null,"name",p.getName());
xs.endTag(null, "tns:classe");
}
xs.endTag(null, "Classes");
xs.endDocument();
os.flush();
os.close();
}
}
最后这是xml文件classe.xml
<?xml version="1.0" encoding="UTF-8"?>
<tns:Classes xmlns:tns="http://www.example.org/classe" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/classe classe.xsd ">
<tns:classe namecls="SmallArc"/>
<tns:classe namecls="SmallBar"/>
<tns:classe namecls="SmallTrunk"/>
<tns:classe namecls="SouthEastLine"/>
<tns:classe namecls="SouthEastLittleLine"/>
</tns:Classes>