dom4j及XPath

1. dom4j解析及乱码问题
dom4j标签查找顺序是:
reader.read(new File("src/exam.xml"))----document------》getRootElement()---------》element("student")或elements ("student").get(int  x)----------》element
 
public void add() throws Exception{
SAXReader reader=new SAXReader();
Document document=reader.read(new File("src/exam.xml"));
 
//在指定位置插入。非XPath取数法
Element student=document.getRootElement().element("student");//注意如查是.elements则返回list集合
List list=student.elements();
Element sex=DocumentHelper.createElement("性别");
sex.setText("女");
list.add(2, sex);
                 //在末尾插入
student.addElement("性别").setText("男");

//XMLWriter writer=new XMLWriter(new FileOutputStream("src/exam.xml"));//不可以用FileWriter,FileWriter写出时,不能指定码表,会乱码
//XMLWriter writer=new XMLWriter(new OutputStreamWriter(new FileOutputStream("src/exam.xml"),"utf-8"));//将会以utf-8读,和写
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
 
XMLWriter writer=new XMLWriter(new FileOutputStream("src/exam.xml"),format);
writer.write(document);
writer.close();
}

2.XPath取数

public class Demo{
public static void main(String[] args) throws DocumentException, IOException{
String username="aaa";
String password="123";
//检测xml文档是否有匹配的用户名和密码
SAXReader reader=new SAXReader();
Document document=reader.read(new File("src/users.xml"));
Node node=document.selectSingleNode( "//user[@username='"+username+"' and @password='"+password+"']");/ /XPath取数,此句有问题,但不知道问题在哪???问题在于没有导入 jaxen-1.1-beta-6.jar包,
if(node==null){
System.out.println("用户名或密码错误!");
}else{
System.out.println("登录成功");
}
}
}  


实例
public class XmlUtils {
private static String filepath;
static{
filepath=XmlUtils.class.getClassLoader().getResource("users.xml").getPath();//为何要取路径。因为类加载器,只加载一次文件,是这样??
}
public static Document getDocument() throws Exception{
SAXReader reader=new SAXReader();
Document document=reader.read(new File(filepath));
return document;
}
public static void write2Xml(Document document) throws IOException{
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
 
XMLWriter writer=new XMLWriter(new FileOutputStream(filepath),format);
writer.write(document);
writer.close();
}
}


Element e=(Element) document.selectSingleNode("//user[@username='"+username+"' and @password='"+password+"']");
注意要导入两个包dom4j-1.6.1.jar,和 jaxen-1.1-beta-6.jar两个包
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值