示例xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<A>
<ONE single="true">
<aa>aa1</aa>
<bb>bb1</bb>
<cc>cc1</cc>
</ONE>
<TWO single="true">
<aa>aa2</aa>
<bb>bb2</bb>
<cc>cc2</cc>
</TWO>
<THREE>
three
</THREE>
</A>
源代码:
package com.mycompany.xmltest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class ARead {
/*
* Reload this method to get text contents within a leaf of any level
*
* @Return null if there is no such a leaf
*/
public Object getXml(String key1, String key2, String key3) {
HashMap retMap = readXmlFile(new File("F://a.xml"));
if (!retMap.isEmpty()) {
Object obj = retMap.get(key1);
if (obj instanceof HashMap) {
retMap = (HashMap) obj;
if (!retMap.isEmpty()) {
obj = retMap.get(key2);
if (obj instanceof HashMap) {
retMap = (HashMap) obj;
if (!retMap.isEmpty()) {
return retMap.get(key3);
}
}
}
}
}
return null;
}
private HashMap readXmlFile(File thefile) {
HashMap map = new HashMap();
BufferedReader bfreader = null;
DocumentBuilder docbuilder = null;
Document doc = null;
try {
bfreader = new BufferedReader(new FileReader(thefile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
docbuilder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
try {
doc = docbuilder.parse(new InputSource(bfreader));
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bfreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (doc.hasChildNodes()) {
NodeList nlist_01 = doc.getChildNodes();
parseChild(nlist_01, map);
}
return map;
}
/*
* Recursive call
*/
private void parseChild(NodeList nlist, HashMap themap) {
for (int i = 0; i < nlist.getLength(); i++) {
Node node = nlist.item(i);
if (node.hasChildNodes()
&& node.getFirstChild().getNextSibling() != null) {
HashMap sonMap = new HashMap();
parseChild(node.getChildNodes(), sonMap);
themap.put(node.getNodeName(), sonMap);
} else {
if (node.getTextContent() != null
&& !"".equals(node.getTextContent())) {
themap.put(node.getNodeName(), node.getTextContent());
}
}
}
}
public static void main(String[] args) {
ARead test = new ARead();
System.out.println(test.getXml("A", "ONE", "aa"));
System.out.println(test.getXml("A", "ONE", "cc"));
System.out.println(test.getXml("A", "TWO", "bb"));
}
}