java创建Xml笔记

java创建Xml4大类:

 

Element:节点类

Attribute属性类

Document:指的就是文档类

XMLOutput:输出类

此类是用java建立一个xml文件

 

public class TestJdom {

    //创建XML(模型)dom

    public static void main(String[] args) {

       createXmlDom();

    }

    public static void createXmlDom(){

       Element beans=new Element("beans");

       Element bean=new Element("bean");

       Attribute id=new Attribute("id","dataSource");

       Attribute clazz=new Attribute("class","org.apache.commons.dbcp.BasicDataSource");

       bean.setAttribute(id);

       bean.setAttribute(clazz);

       beans.addContent(bean);

      

       Map<String ,String> map=new HashMap<String,String>();

       map.put("driverClassName", "com.mysql.jdbc.Driver");

       map.put("username", "root");

       map.put("password", "root");

       map.put("url", "jdbc:mysql://localhost:3306/test");

      

       for(Map.Entry<String,String> mapEntry:map.entrySet()){

           Element property=new Element("property");

           property.setAttribute("name", mapEntry.getKey());

           Element value=new Element("value");

           value.setText(mapEntry.getValue());

          

           property.addContent(value);

           bean.addContent(property);

       }

       Document doc=new Document(beans);

       XMLOutputter outputter=new XMLOutputter(Format.getPrettyFormat());

           try {

              outputter.output(doc, System.out);

              outputter.output(doc, new FileOutputStream(System.getProperty("user.dir")+File.separator+"spring.xml"));

              //System.getProperty("user.dir"):系统的根路径,

           } catch (FileNotFoundException e) {

              e.printStackTrace();

           } catch (IOException e) {

              e.printStackTrace();

           }

    }

}

XMl解析:

Dom解析:小型,一次把所有xml读到内存中

sax解析:比较适合大型的文本

jdom是一个组件,融合了两个解析的优点。

以下例子是从xml文件中读取值:

public static void parseXml() throws JDOMException, IOException{

       SAXBuilder builder=new SAXBuilder();

       Document doc=builder.build(new File(System.getProperty("user.dir")+File.separator+"spring.xml"));

       Element beans=doc.getRootElement();

       Element bean=beans.getChild("bean");

      

       String id=bean.getAttributeValue("id");

       String clazz=bean.getAttribute("class").getValue();

       String clazz1=bean.getAttributeValue("class");

//     System.out.println(id+"-------->"+clazz);

//     System.out.println(id+"-------->"+clazz1);

          

       List <Element> properties=bean.getChildren("property");

       for(Element property:properties){

           String name=property.getAttributeValue("name");

           String value=property.getChildText("value");

//         System.out.println(name+"---------->"+value);

       }

    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值