用java创建Xml的4大类:
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); } } |