1,单层对象解析
String str = "<string xmlns=\"http://tempuri.org/\">I live in China。我在中国。</string>";
2,代码
public static void main(String[] args) {
try{
String str = "<string xmlns=\"http://tempuri.org/\">I live in China。我在中国。</string>";
Document doc = null;
try {
doc = DocumentHelper.parseText(str);
} catch (DocumentException e2) {
e2.printStackTrace();
}
Element root = doc.getRootElement();// 指向根节点
System.out.println("start.getTextTrim()=" + root.getTextTrim());//获取根节点文本内容
} catch (Exception e) {
e.printStackTrace();
}
}
输出结果:
-----------------------------------------------------------------------------分界线----------------------------------------------------------------------
1,多层对象解析
<string xmlns=\"http://tempuri.org/\">
<p><li>I live in China。我在中国。</li><li>My home is in hubbe。</li></p>
<p>I speak Chinese。我会说中文。</p>
</string>
2,代码
public static void main(String[] args) {
try{
String str = "<string xmlns=\"http://tempuri.org/\">" +
"<p><li>I live in China。我在中国。</li><li>My home is in hubbe。</li></p>" +
"<p>I speak Chinese。我会说中文。</p>" +
"</string>";
Document doc = null;
try {
doc = DocumentHelper.parseText(str);
} catch (DocumentException e2) {
e2.printStackTrace();
}
Element root = doc.getRootElement();// 指向根节点
// p解析
List<Element> elementList = root.elements("p");//获取所有同级p标签
System.out.println("p2.getTextTrim():" + elementList.get(1).getText());
System.out.println("p2.getTextTrim():" + elementList.get(1).asXML());
try {
Element p = root.element("p");//获取第一个p标签
List lstTime = p.elements("li");// 所有的Item节点
for (int i = 0; i < lstTime.size(); i++) {
Element etime = (Element) lstTime.get(i);
System.out.println("root【"+i+"】.getTextTrim():" + etime.getTextTrim());
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}