import org.w3c.dom.*; // create a Document object from an XML file DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new File("example.xml")); // get the root element of the XML document Element root = doc.getDocumentElement(); // get the name of the root element String rootName = root.getNodeName(); System.out.println("The root element is: " + rootName);
import org.jsoup.*; import org.jsoup.nodes.*; // create a Document object from an HTML file Document doc = Jsoup.parse("Both of these examples use the `getNodeName()` method to get the name of a node in an XML or HTML document. In Example 1, the XML document is parsed using the `DocumentBuilder` class and the root element is retrieved using `getDocumentElement()`. In Example 2, the HTML document is parsed using the `Jsoup` library and the title element is retrieved using `select()`.Example Hello world!
"); // get the title element of the HTML document Element title = doc.select("title").first(); // get the name of the title element String titleName = title.nodeName(); System.out.println("The title element is: " + titleName);