Java JDOM Document setRootElement() 方法



Java JDOM 的 setRootElement() 方法是 Document 类的一个方法,用于设置 XML 文档的根元素。此方法可用于将根元素设置为任何空文档。如果此方法用于已经具有根元素的文档,则会替换根元素。

语法

以下是 Java JDOM Document setRootElement() 方法的语法:

Document.setRootElement(rootElement);

参数

Java setRootElement() 方法接受一个参数。

rootElement - 表示我们需要设置为根元素的 Element 对象。

返回值

Java setRootElement() 方法在设置新的根元素后返回修改后的文档。

示例 1

Java setRootElement(root) 方法在以下 Java 程序中用于一个空的 JDOM 文档。首先,创建一个名为 'company' 的 Element 对象,然后使用 setRootElement() 方法将其设置为根元素。

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.XMLOutputter;

public class SetRootElement {
   public static void main(String args[]) {
      try {	
    	 //Create a new Document
	     Document doc = new Document();
	     //Create root Element
	     Element root = new Element("company").setText("xyz");
	     //Add root Element
	     doc.setRootElement(root);
	     //Print document
	     XMLOutputter xmlOutput = new XMLOutputter();
         xmlOutput.output(doc, System.out);        
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

输出窗口显示设置根元素后的 XML 文档。

<?xml version="1.0" encoding="UTF-8"?>
<company>xyz</company>

示例 2

以下是我们需要为其设置新根的 EmpData.xml 文件:

<Company>
   <Employee>John</Employee>
   <Employee>Daniel</Employee>
</Company>

setRootElement(root) 方法用于将新的根元素设置为已存在的 EmpData.xml 文件。此方法完全替换根元素及其子元素为新的根元素。

import java.io.File;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class SetRootElement {
   public static void main(String args[]) {
      try {	
    	 //Reading the XML file
 		 SAXBuilder saxBuilder = new SAXBuilder();
 		 File inputFile = new File("EmpData.xml");			          
 		 Document doc = saxBuilder.build(inputFile);		 
 		 //Print original document 
	     XMLOutputter xmlOutput = new XMLOutputter();
	     xmlOutput.setFormat(Format.getPrettyFormat());
	     System.out.println("------Document BEFORE setting the Root-------");
         xmlOutput.output(doc, System.out);
	     //Create root Element
	     Element root = new Element("college").setText("xyz");
	     //Add root Element
	     doc.setRootElement(root);
	     //Print document after setting root
	     System.out.println("\n"+"------Document AFTER setting the Root-------");
         xmlOutput.output(doc, System.out);        
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

输出窗口显示设置根元素前后文档的内容。

------Document BEFORE setting the Root-------
<?xml version="1.0" encoding="UTF-8"?>
<Company>
  <Employee>John</Employee>
  <Employee>Daniel</Employee>
</Company>

------Document AFTER setting the Root-------
<?xml version="1.0" encoding="UTF-8"?>
<college>xyz</college>
广告

© . All rights reserved.