二:XML和HTML区别简单来说,xml就是一种符合格式的文本文件,这种文件有一种简单的格式,可以用来储存一些数据
xml是互联网数据传输的重要工具,它可以跨越互联网任何的平台,不受编程语言和 *** 作系统的限制
三:XML语法XML设计出,是为了在网络中采取这种格式传送数据
HTML设计出,是为了吧数据显示在网络页面上
必须有XML声明语句 (第一行) 必须有且仅有一个根元素 标签成对 元素正确嵌套 【拥有正确语法的 XML 被称为“形式良好”的 XML】
四:java使用第三方工具包【dom4j】,解析XML文件 4.1:dom4j工具包下载George John Reminder Don't forget the meeting!
jar包下载路径
4.2:解析Demohttps://dom4j.github.io/
zhangsan 18李四 19wangwu 17java
public static void main(String[] args) throws documentException { //1.构建SAXReader输入流 SAXReader reader = new SAXReader(); //2.加载xml文件,获取document对象 document document = reader.read("src/persons.xml"); //3.获取根元素 Element root = document.getRootElement(); //Persons //4.获取标签名 System.out.println(root.getName()); //5.获取所有的子元素,遍历子元素 List4.3:修改XML文件信息list = root.elements(); list.forEach(e->{ System.out.println("------->"+e.getName()); //Person Student Iterator it = e.elementIterator(); while(it.hasNext()){ Element son = it.next(); System.out.println("------->--------->"+son.getName()); System.out.println("------->--------->"+son.getText()); if(son.attributevalue("value")!=null && son.attributevalue("value")!=""){ System.out.println("value属性 = "+son.attributevalue("value")); } } }); }
public static void main(String[] args) throws IOException { writeToFile(createdocument()); } //创建document,插入元素与属性 public static document createdocument(){ //1.创建document对象 document document = documentHelper.createdocument(); //2.插入节点 Element root = document.addElement("School"); Element bjSchool = root.addElement("bjSchool"); Element shSchool = root.addElement("shSchool"); bjSchool.addAttribute("id","1"); shSchool.addAttribute("id","2"); bjSchool.addElement("name").addText("北京校区"); bjSchool.addElement("location").addText("望京"); shSchool.addElement("name").addText("上海校区"); Element shlocation = shSchool.addElement("location").addText("浦东"); //删除元素 //shSchool.remove(shlocation); //修改 shlocation.addText("上海浦东"); //追加 shlocation.setText("浦东新区"); //修改,覆盖 shlocation.setName("shlocation"); //修改标签名 shSchool.attribute("id").setValue("02"); //修改属性 return document; } //写出document到文件 public static void writeToFile(document document) throws IOException { //1.输出流 XMLWriter XMLWriter writer = null; //2.定义输出格式 OutputFormat format = OutputFormat.createPrettyPrint(); writer = new XMLWriter(new FileWriter("src/school.xml"),format); //3.写出 writer.write(document); //4.刷出 writer.flush(); //5.关闭 writer.close(); }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)