Usage and examples of Element getRootElement()

`getRootElement()` is a Java method for getting the root element of an XML document. In a DOM (Document Object Model) parser, every XML document has a root element that is the parent of all other elements. Here is the usage and example of this method:

**Usage**
```
public Element getRootElement()
```

**Return Value**
- returns the root element (Element object) of the XML document (Document)

**Example**
Suppose we have an XML file called "myXML.xml" with the following content:

```xml
<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
   </book>
</catalog>
```

Use the `getRootElement()` method to parse the file and get its root element:
```java
import org.w3c.dom.*;
import javax.xml.parsers.*;

public class Main {
    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse("myXML.xml");

        Element root = doc.getRootElement();
        System.out.println("Root element : " + root.getNodeName());
    }
}
```

Output:
```
Root element : catalog
```

This example creates a `DocumentBuilderFactory` instance and then uses it to create a `DocumentBuilder`. The `DocumentBuilder` will then be used to parse the XML file and return the result as a `Document`. Finally, the root element `root` of the XML document can be obtained through the `getRootElement()` method.

Guess you like

Origin blog.csdn.net/qq_70143756/article/details/130971714