方法一:
String s_xml1 = "" +
"
lalalalal" +"
1234" +"";
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(s_xml1)));
Element element = document.getDocumentElement();
NodeList childNodes = element.getChildNodes();
if (childNodes != null) {
for (int i = 0; i < childNodes.getLength(); i++) {
Node item = childNodes.item(i);
String name = item.getNodeName();
String nodeValue = item.getNodeValue();
String textContent = item.getTextContent();
Log.i("xx-----", name + "---" + nodeValue + "---" + textContent);
}
}
} catch (Exception e) {
e.printStackTrace();
}
方法二:
public void s() {
//创建一个DocumentBuilderFactory的对象
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//创建一个DocumentBuilder的对象
String xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
";StringReader sr = new StringReader(xmlStr);
InputSource is = new InputSource(sr);
HashMap hashMap = new HashMap();
try {
//创建DocumentBuilder对象
DocumentBuilder db = dbf.newDocumentBuilder();
//通过DocumentBuilder对象的parser方法加载books.xml文件到当前项目下
Document document = db.parse(is);
//获取所有book节点的集合
NodeList bookList = document.getElementsByTagName("title");
//通过nodelist的getLength()方法可以获取bookList的长度
System.out.println("一共有" + bookList.getLength() + "个title节点");
for (int i = 0; i < bookList.getLength(); i++) {
Node book = bookList.item(i);
NamedNodeMap attrs = book.getAttributes();
System.out.println("第 " + (i + 1) + "个title节点共有" + attrs.getLength() + "个属性");
for (int j = 0; j < attrs.getLength(); j++) {
//通过item(index)方法获取book节点的某一个属性
Node attr = attrs.item(j);
if (attr.getNodeName().equals("CONTENT")) {
String name = attr.getNodeName();
String value = attr.getNodeValue();
//获取属性名
// System.out.print("属性名:" + name);
//获取属性值
// System.out.println("--属性值: " + value);
String[] splitValue = value.split(",");
for (int k = 0; k < splitValue.length; k++) {
String resultValue = splitValue[k];
String[] splitResult = resultValue.split("=");
hashMap.put(splitResult[0], splitResult[1]);
}
}
}
}
for (String key : hashMap.keySet()) {
System.out.println("key= " + key + " and value= " + hashMap.get(key));
}
} catch (Exception e) {
e.printStackTrace();
}
}