java解析xml格式的String字符串,不是xml文件
源代码如下:-----------------------------------------------------------------packagecart.bi...
源代码如下:
-----------------------------------------------------------------
package cart.biz;
import org.dom4j.*;
import org.jaxen.*;
import org.jaxen.XPath;
//import org.dom4j.io.SAXReader;
import java.util.List;
public class XmlDemo {
public static void main(String[] args) throws Exception {
System.out.println("Id: ");
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 = (XPath) 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);
}
}
}
--------------------------------------------------------------------------------------
现在这个几个包:dom4j-1.6.1.jar,jaxen-1.1-beta-7.jar都包含进去了,怎么出现异常如下:
Exception in thread "main" java.lang.ClassCastException: org.dom4j.xpath.DefaultXPath
at cart.biz.XmlDemo.main(XmlDemo.java:17)
如何解决? 展开
-----------------------------------------------------------------
package cart.biz;
import org.dom4j.*;
import org.jaxen.*;
import org.jaxen.XPath;
//import org.dom4j.io.SAXReader;
import java.util.List;
public class XmlDemo {
public static void main(String[] args) throws Exception {
System.out.println("Id: ");
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 = (XPath) 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);
}
}
}
--------------------------------------------------------------------------------------
现在这个几个包:dom4j-1.6.1.jar,jaxen-1.1-beta-7.jar都包含进去了,怎么出现异常如下:
Exception in thread "main" java.lang.ClassCastException: org.dom4j.xpath.DefaultXPath
at cart.biz.XmlDemo.main(XmlDemo.java:17)
如何解决? 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询