java如何解析xml格式的字符串
String result="<a>
<b id="1" name="sda" age="23"></b>
<b id="2" name="sss" age="2"></b>
<b id="3" name="sdf" age="45"></b>
</a>";
请问各位大神用dom4j还是jdom解析这个字符串result,最好有代码演示,谢谢!
[最优解释]
个人喜欢Dom4j
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import java.util.List;
public class XmlDemo {
public static void main(String[] args) throws Exception {
String str = "<a>" +
"<b id="1" name="sda" age="23"></b>" +
"<b id="2" name="sss" age="2"></b>" +
"<b id="3" name="sdf" age="45"></b>" +
"</a>";
Document doc = DocumentHelper.parseText(str);
XPath xpathSelector = DocumentHelper.createXPath("//b");
List nodes = xpathSelector.selectNodes(doc);
for (Object obj : nodes) {
Element n = (Element) obj;
String id = n.attribute("id").getText();
String name = n.attribute("name").getText();
String age = n.attribute("age").getText();
System.out.println("Id: " + id + ", Name: " + name + ", Age: " + age);
}
}
}