DOM4J+Xpath

第一步:引用jar包

   dom4j-1.6.1.jar

   jaxen-1.1-beta-6.jar(支持XPath必须的,否则会报错java.lang.NoClassDefFoundError: org/jaxen/JaxenException,此jar包可以从dom4j的lib文件夹中获得)

第二步:XPath基本语法

   http://www.w3school.com.cn/xpath/index.asp

第三步:实例

users.xml

<? xml version="1.0" encoding="UTF-8" ?>
- < Users >
- < User id =" 0 " >
  < Name > youchuancong </ Name >
  < Age > 23 </ Age >
  </ User >
- < User id =" 1 " >
  < Name > cindy </ Name >
  < Age > 23 </ Age >
  </ User >
  </ Users >

 

XMLTools.java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class XMLTools {
public void creat(String filename){//创建xml文件
 Document document = DocumentHelper.createDocument();
    Element usersElement = document.addElement("Users");
  
    Element userElement =  usersElement.addElement("User");
    userElement.addAttribute("id", "0");
   
    Element nameElement=userElement.addElement("Name");
    nameElement.setText("youchuancong");
   
    Element  ageElement=userElement.addElement("Age");
    ageElement.setText("23");
   
    Element userElement1 =  usersElement.addElement("User");
    userElement1.addAttribute("id", "1");
   
    Element nameElement1=userElement1.addElement("Name");
    nameElement1.setText("cindy");
   
    Element  ageElement1=userElement1.addElement("Age");
    ageElement1.setText("23");
   
   try{
   XMLWriter output = new XMLWriter(
           new FileWriter( new File(filename) ));
       output.write( document );
       output.close();
       }
    catch(IOException e){System.out.println(e.getMessage());}
}

public void read(String filename,String id) throws Exception{//根据id读出学生姓名
 SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(new File(filename));
    Element e = (Element)document.selectSingleNode("/Users/User[@id='"+id+"']");
    Element name = e.element("Name");
    System.out.println("Name:"+name.getText());
 
}
public void readName(String filename) throws Exception{//读出所有学生的学生姓名
 SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(new File(filename));
    List users = document.selectNodes("//Name");
    Iterator it = users.iterator();
    while(it.hasNext()){
     Element e = (Element)it.next();
     System.out.println("Name:"+e.getText());
    }
   
   
 
}
public void addUser(String filename,String id,String name,String age) throws Exception{
 SAXReader saxReader = new SAXReader();//添加信息
    Document document = saxReader.read(new File(filename));
    Element e = (Element)document.selectSingleNode("/Users");
  // Element e =  document.getRootElement();
   Element user = e.addElement("User");
   user.setAttributeValue("id", id);
   user.addElement("Name").setText(name);
   user.addElement("Age").setText(age);
  
     XMLWriter output = new XMLWriter(
             new FileWriter( new File(filename) ));
         output.write( document );
         output.close();
}
public void readUser(String filename) throws Exception{//读出所有学生的基本信息
 SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(new File(filename));
    List l = document.selectNodes("/Users/User");
    Iterator it = l.iterator();
    while(it.hasNext()){
     Element e = (Element)it.next();
     System.out.println("id:"+e.attributeValue("id"));
     Element name = e.element("Name");
     System.out.println("name:"+name.getText());
     Element age = e.element("Age");
     System.out.println("age:"+age.getText());
     System.out.println("#############################");
    }
   
}

public void delete(String filename,String id) throws Exception{//删除指定id的学生
 SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(new File(filename));
    Element e = (Element)document.selectSingleNode("/Users/User[@id='"+id+"']");
    if(e!=null){
     Element parent = e.getParent();
     parent.remove(e);
    
      XMLWriter output = new XMLWriter(
               new FileWriter( new File(filename) ));
          output.write( document );
          output.close();
    }
}

 


public void readAll(String filename) throws Exception{//选取所有节点
 SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(new File(filename));
    List users = document.selectNodes("//*");
    Iterator it = users.iterator();
    while(it.hasNext()){
     Element e = (Element)it.next();
     System.out.println("ElementName:"+e.getName()+"||value:"+e.getText());
    }
   
   
 
}
public void modify(String filename,String id,String name) throws Exception{//修改指定学号的学生姓名
 SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(new File(filename));
    Element e = (Element)document.selectSingleNode("/Users/User[@id='"+id+"']");
    Element n = e.element("Name");
    n.setText(name);
  
     XMLWriter output = new XMLWriter(
             new FileWriter( new File(filename) ));
         output.write( document );
         output.close();
       
}
}

 

XMLTest.java
public class XMLTest {
 public static void main(String[] args) {
  XMLTools xml = new XMLTools();
  //xml.creat("users.xml");
  try {
   //xml.read("users.xml", "0");
   //xml.addUser("users.xml", "4", "no", "100");
   //xml.readUser("users.xml");
   //xml.readName("users.xml");
   xml.readAll("users.xml");
   //xml.modify("users.xml", "0", "helloworld");
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
NestJS 是一个用于构建高效、可扩展的服务器端应用程序的框架,它基于 TypeScript 编写,并且使用了面向对象的编程(OOP)和函数式编程(FP)的最佳实践。XPath 是一种用于在 XML 文档中定位节点的语言。在 NestJS 中使用 XPath 可以方便地对 XML 数据进行解析和处理。 在 NestJS 中使用 XPath,你可以按照以下步骤进行操作: 1. 首先,安装相关的依赖包。你可以使用 npm 或者 yarn 进行安装,例如: ``` npm install xpath ``` 2. 在你的 NestJS 项目中引入 xpath 模块: ```typescript import * as xpath from 'xpath'; ``` 3. 使用 xpath 模块的 `select` 方法来选择符合条件的节点。例如,假设你有一个 XML 文档如下: ```xml <bookstore> <book category="cooking"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="children"> <title lang="en">Harry Potter</title> <author>J.K. Rowling</author> <year>2005</year> <price>29.99</price> </book> </bookstore> ``` 你可以使用以下代码来选择所有书籍的标题: ```typescript const xml = // your XML document as a string const doc = new DOMParser().parseFromString(xml, 'application/xml'); const select = xpath.useNamespaces({ 'ns': 'http://www.w3.org/1999/xhtml' }); const nodes = select('//ns:book/ns:title', doc); for (const node of nodes) { console.log(node.textContent); } ``` 这样就可以打印出所有书籍的标题。 希望以上信息对你有所帮助!如果你有任何其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值