您好,登录后才能下订单哦!
这篇文章主要介绍“JDom如何新建和读取xml”,在日常操作中,相信很多人在JDom如何新建和读取xml问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”JDom如何新建和读取xml”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
//package xml;
import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.List;
//import org.jdom.*;
import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
public class test {
private static String titlename;
private String chapter;
private String topic;
 
 public static void main(String [] msg){
    wriXml();
    // try{
     readXml();
  //    }catch (Exception e){e.printStackTrace();}
 }
 public static void readXml() {  
    SAXBuilder builder=new SAXBuilder();
   try{
    Document document=builder.build(new File("contents.xml"));
    Element root=document.getRootElement();
    Element title=root.getChild("title");
    System.out.println(title.getText());   
   
    Element contents=root.getChild("contents");
    List lis=contents.getChildren("chapter");
    Iterator it=lis.iterator();
    while(it.hasNext()){
       Element chapter=(Element) it.next();
       System.out.println(chapter.getAttribute("title"));
     }
    }catch(Exception e){e.printStackTrace();}
    
    
}
public static void wriXml(){
Element ele=new Element("boot");
    Document doc=new Document(ele);
    
    ele.addAttribute(new Attribute("vin","123456789"));
    ele.addContent(new Element("first").addContent("guoxb"));
    ele.addContent(new Element("second").addContent("30"));
    ele.addContent(new Element("third").addContent("univercity")); 
    ele.addContent(new Element("first").addContent("girlfri").addAttribute("name","22"));      
    ele.addContent(new Element("right"));
    ele.addContent(new Comment("这是一条主释"));
    Element gg=ele.getChild("right");
        gg.addContent(new Element("pkg").addContent("thhhhhhhh"));
    
    //访问子元素
    Element fir=ele.getChild("first");
    //去处子元素
    boolean remo=ele.removeChild("first");
    
    //打印输出xml
    try{
      XMLOutputter out=new XMLOutputter(" ",true);
        out.setEncoding("gb2312");
        out.output(doc,System.out);
          
    //保存到xml文档中
    FileWriter fi=new FileWriter("./gxb.xml");
    out.output(doc,fi);
    fi.close();         }catch (Exception e){e.printStackTrace();}
  }
}
[@more@]
到此,关于“JDom如何新建和读取xml”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。