方法一:
String s\_xml1 = "<xml>" +
"<head>lalalalal</head>" +
"<body>1234</body>" +
"</xml>";
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\\"?><html><head><title METANAME=\\"MobilePayPlatform\\" CONTENT=\\"amount=1,amt\_type=RMB,mer\_date=20180619,mer\_id=69002429,mer\_priv=7242A100005259,order\_id=707794189,platDate=20180619,ret\_code=00200014,ret\_msg=支付结果不明,请稍后调用订单查询接口获取订单状态!,sign\_type=RSA,trade\_state=TRADE\_FAIL,version=4.0,sign=rZhSnK+5zMzEoeKAODq0liT0BdPjqjkSKJTHrGzuHJLPJ3gsrS8qh06C5ZM0qHOG8FGmTlPq22VBAgPDMSsM8zvKTTKGDlwbSBzAZ8U1xMsewo+/w6tRHWlT39rKo1CreIKZ1OSDtiyTPy+DKnGey6AEohB3Y52zPROTiBH5nz8=\\"/></head><body></body></html>";
StringReader sr = new StringReader(xmlStr);
InputSource is = new InputSource(sr);
HashMap<String, String> hashMap = new HashMap<String, String>();
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();
}
}
### 转载至链接:https://my.oschina.net/u/3309...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。