linux cpu占用率如何看
235
2022-09-20
Dom4J读写xml
解析读取XML
public static void main(String[] args) { //1获取SaxReader对象 SAXReader reader=new SAXReader(); try { //2使用Saxrreader对象加载xml文件,返回Document对象 Document document=reader.read(new File("student.xml")); //3使用document对象或根元素 Element rootele=document.getRootElement(); //4获取子元素的集合(获取的是student子元素的集合) List
向xml文件中添加节点并写入文件保存;
public static void main(String[] args) { //1创建SaxReader对象 SAXReader reader=new SAXReader(); try { //2读取xml文档,并返回document对象 Document document=reader.read(new File("student.xml")); //3获取根元素 Element rootele=document.getRootElement(); //4在根元素下添加student子元素 Element st_ele=rootele.addElement("student"); //在新增的student元素下添加其他子元素 Element sid_ele=st_ele.addElement("sid"); Element sname_ele=st_ele.addElement("sname"); Element sex_ele=st_ele.addElement("sex"); Element address_ele=st_ele.addElement("address"); Element age_ele=st_ele.addElement("age"); //在每个子元素下添加内容 Scanner sc=new Scanner(System.in); System.out.println("输入编号:"); sid_ele.setText(sc.next()); System.out.println("输入姓名:"); sname_ele.setText(sc.next()); System.out.println("输入性别:"); sex_ele.setText(sc.next()); System.out.println("输入地址:"); address_ele.setText(sc.next()); System.out.println("输入年龄:"); age_ele.setText(sc.next()); //创建字节输出流对象 FileOutputStream fout=new FileOutputStream("student.xml"); //创建缓冲区字符输出流对象 BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(fout, "utf-8")); //写文档到xml文件 document.write(bw); bw.flush(); bw.close(); System.out.println("增加成功!"); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
修改xml 文件中的节点并写入文件保存;
public static void main(String[] args) { Scanner sc=new Scanner(System.in); //1创建SaxReader对象 SAXReader reader=new SAXReader(); try { //2读取xml文档,并返回document对象 Document document=reader.read(new File("student.xml")); //3获取根元素 Element rootele=document.getRootElement(); //4获取student子元素的集合 List
删除xml文件中的节点
public static void main(String[] args) { Scanner sc=new Scanner(System.in); //1创建SaxReader对象 SAXReader reader=new SAXReader(); try { //2读取xml文档,并返回document对象 Document document=reader.read(new File("student.xml")); //3获取根元素 Element rootele=document.getRootElement(); //获取要移除的学生编号 System.out.println("请输入要删除的学生编号:"); String sid=sc.next(); //获取student元素的集合 List
xml读写的工具类方法示例
/** * 将Document对象写入到xml文件 * @throws IOException * */ public static void XmlToFile(Document doc) throws IOException{ //创建字节输出流对象 FileOutputStream fout=new FileOutputStream(new File("student.xml")); //创建字节流缓冲区,加快写出速度 BufferedOutputStream bout=new BufferedOutputStream(fout); //创建字符输出流对象 BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(bout, "utf-8")); doc.write(bw); bw.flush(); bw.close(); System.out.println("写xml文件成功"); } /** * 从xml文件中获取学生的对象集合 * */ public static List
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~