你的位置:首页 > Java教程

[Java教程]Java Dom4j XML用法总结

1、新建             Document doc = DocumentHelper.createDocument();
            Element root = doc.addElement( "ocs");
            root.addElement( "header");
            Element body = root.addElement( "body");
            Element fontnode = body.addElement( "font");
            fontnode.addAttribute( "size", "9");
            System. out.println(root.as
 
2、打开现有
           Document doc = DocumentHelper.parseText(            Node node = doc.selectSingleNode( "ocs/body/font");    
             if (node instanceof Element)
            {
                  Element pnode = (Element) node;           
                  Attribute attr = pnode.attribute( "size");
                  System. out.println(attr.as
            }
 
          Dom4j中内置了XPath,因此可以在selectSingleNode中象XPath那样访问路径字符串;
          注意:需要引用jaxen-1.1.1.jar包,否则selectSingleNode会产生异常并返回Null;
 
3、打开现有文档(从文件导入):
          SAXReader saxReader = new SAXReader();
          Document document = saxReader.read( );
 
4、将Document写入到文件中:
          try
            {
                   new  new FileWriter( new File()));
                  output.write( doc);
                  output.close();
            } catch (IOException e)
            {
                  System. out.println(e.getMessage());
            }