JSP应用开发与实践 教学课件 作者 刘乃琦 王冲 第12章 JSP操作XML.ppt
文本预览下载声明
使用DocumentHelper类的createDocument()方法可以创建一个XML文档对象。创建XML文档对象的具体代码如下: Document document = DocumentHelper.createDocument(); 说明: DocumentHelper类保存在org.dom4j包中。 另外,使用DocumentFactory对象也可以创建一个XML文档对象。DocumentFactory对象由DocumentFactory类的getInstance()静态方法产生。通过DocumentFactory对象创建XML文档对象的具体代码如下: DocumentFactory documentFactory= DocumentFactory.getInstance(); Document document=documentFactory.createDocument(); 说明: DocumentFactory类保存在org.dom4j包中。 12.3.1 创建XML文档对象 为XML文档创建根节点,首先需要创建一个普通节点,然后再通过调用Document对象的setRootElement()方法把该节点设置为根节点。创建普通节点可以通过DocumentHelper对象的createElement()方法实现。下面将对DocumentHelper对象的createElement()方法和Document对象的setRootElement()方法进行详细介绍。 DocumentHelper对象的createElement()方法 DocumentHelper对象的createElement()方法的用于创建一个普通的节点,其方法原型如下: public static Element createElement(String name) name:用于指定要创建的节点名。 Document对象的setRootElement()方法 Document对象的setRootElement()方法用于将指定的节点设置为根节点,其方法原型如下: public void setRootElement(Element rootElement) rootElement:用于指定要作为根节点的普通节点。 例如,创建一个只包括一个根节点的XML文档的具体代码如下: Document document = DocumentHelper.createDocument(); //创建XML文档对象 Element placard=DocumentHelper.createElement(placard); //创建普通节点 document.setRootElement(placard); // 将placard设置为根节点 12.3.2 创建根节点 在创建XML文档时,为了便于阅读和理解,经常需要在XML文档中添加注释。通过dom4j组件的Element对象的addComment()方法可以为指定的节点添加注释。Element对象的addComment()方法的原型如下: public Element addComment(String comment) comment:用于指定注释内容。 例如,为XML文档的根节点添加注释的代码如下: Document document = DocumentHelper.createDocument(); //创建XML文档对象 Element placard=DocumentHelper.createElement(placard); //创建普通节点 document.setRootElement(placard); // 将placard设置为根节点 placard.addComment(这是根节点); //添加注释 12.3.3 添加注释 在创建XML文档时,经常需要为指定的节点添加属性。通过dom4j组件的Element对象的addAttribute()方法可以为指定的节点添加属性。Element对象的addAttribute()方法的原型如下: public Element addAttribute(String name,String value) name:用于指定属性名。 value:用于指定属性值。 例如,为XML文档的根节点添加version属性的代码如下: Document document = DocumentHelper.createDocument(); //创建XML文档对象 Element placard=DocumentHelper.createElement(placard); //
显示全部