50,527
社区成员
发帖
与我相关
我的任务
分享
public class Operation_XMl {
private Document doc;
public Operation_XMl(Context context, int nodeId) {
SAXReader reader = new SAXReader();
try {
this.doc = reader.read(context.getAssets().open("PostXML.xml"));
this.SetSingleBody(nodeId);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void SetSingleBody(int nodeId) {
Node node1= this.doc.selectSingleNode("/Root");
Node node2= this.doc.selectSingleNode("/Root/PostNode[@id='1']");
Node node3= node1.selectSingleNode("PostNode");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<Root>
<PostNode id="1" description="查询签到" nextstep="0" dedelay="3000">
</PostNode>
</Root>
Node node3 = node1.selectSingleNode("/Root/PostNode[@id='1']");
System.out.println(node3.getName());//PostNode
System.out.println(((Element)node3).attributeValue("description"));//查询签到
附带我的包:
dom4j-1.6.1.jar
jaxen-1.1-beta-6.jar
就这两个就够了,第一个基础,第二个使用xpath时候引入就可以,一般也不用,大项目都是用xstream对象化,基本不会这样手动去拆,不好维护不说而且重复工作太大,违背面向对象的设计import java.io.File;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class Dom4jTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
SAXReader reader = new SAXReader();
reader.setEncoding("utf-8");
Document document = null;
try {
System.out.println(System.getProperty("user.dir"));
document = reader.read(new File("src/test/PostXML.xml"));
} catch (Exception ex) {
ex.printStackTrace();
}
Node node1 = document.selectSingleNode("Root");
System.out.println(node1.getName());
Node node2 = node1.selectSingleNode("PostNode");
System.out.println(node2.getName());
System.out.println(((Element)node2).attributeValue("dedelay"));
System.out.println(((Element)node2).attributeValue("description"));
}
}