EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials XML Tutorial XML root element
Secondary Sidebar
XML Tutorial
  • Basic
    • What is XML?
    • XML Tags
    • XML URL
    • XPath Sibling
    • XML root element
    • XML Encryption
    • XML Parsing php
    • xml parsing with java
    • Dataset XML
    • XML Parser in C#
    • XML Tree
    • XML boolean
    • XML sitemap
    • XML Array
    • XML reserved characters
    • XML Viewer
    • XML Uses
    • XML Special Characters
    • XML generator
    • XML file format
    • XML DOM
    • XML ampersand
    • XML Mapping
    • XML File
    • XML Element
    • XML HttpRequest
    • XML XSD
    • XML Schema
    • XML Namespaces
    • XML Comments
    • XML Attributes
    • XML Encoding
    • XML Validation
    • XML CDATA
    • XML Database
    • XML Technologies
    • XML Error
    • XML DTD
    • XML Date
    • XML Parsers
    • String in XML
    • XML with CSS
    • XML Versions
    • XML Features
    • XML Commands
    • Servlet web.xml
    • XPath Injection
    • XPath Functions
    • XPath starts-with
    • XPath Selector
    • XPath Count
    • XPath XML
    • XML Parsing in Oracle
    • XML parsing in python
  • Xpath
    • What is XPath?
    • XPath namespace
    • XPath for JSON
    • XPath Last Element
    • Xpath Substring
    • XPath First Element
    • XPath local-name
    • XPath Multiple Attributes
    • XPath Matches
    • XPath Position
    • XPath Index
    • XPath regex
    • XPath id contains
    • XPath innertext
    • XPath Multiple Conditions
    • XPath Helper
    • XPath Generator
    • XPath ID
    • XPath Locator

XML root element

XML root element

Introduction to XML root element

XML root element is defined as a primary element or top-most element in an XML file as XML documents are constructed as an element tree that starts at a root element. This single root element encapsulates further elements together with the default open and close tags’ annotation named @XmlRootElement is used to specify the default root element.

Syntax:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

The XML Schema Definition defines as:

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,883 ratings)
<?xml version="1.0" encoding="UTF-8"?>
<root element>
…..// other child elements
</root element>

The Syntax might go wrong if the root element has more than once in the Document. To write a root element we need to follow the above description. The Structure starts with an XML Prolog followed by the format opening of the root node and ends with the closing tag of the root element. We could notice how the root element encloses other child elements in it.

How does the root element work in XML?

Generally, a mark-up language has the first element to be considered as a root element. In HTML <html> is a root element but in XML user-defined any tag element is a root element. Every Document should have a root element by default that is descendants with child elements and sub-child elements. Let’s take a sample code to see how root elements work.

<?xml version="1.0" encoding="UTF-8"?>
<YouTube>
<Channel>Blipi-An educational Tour</Channel>
<from> United States Of America</from>
<Concept>Kids Learning Management</Concept>
<Subscribers>From different countries</Subscriber>
</YouTube>

In the above code, listing <YouTube> element is a root element and <from>, <concept> are child elements to work with. If Suppose a code has

<?xml version="1.0" encoding="UTF-8"?>
<Channel>Blipi-An educational Tour</Channel>
<from> United States Of America</from>
<Concept>Kids Learning Management</Concept>
<Subscribers>From different countries</Subscriber>

This gives out an error because it doesn’t seem to have a root element.

With DTD XML starts like

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE You Tube channel SYSTEM
"http://picasashop.web.in.edu/dtd/employee.dtd">
<YouTube>
<Channel>Blipi-An educational Tour</Channel>
<from> United States Of America</from>
<Concept>Kids Learning Management</Concept>
<Subscribers>From different countries</Subscriber>
</YouTube>

Coming to java Parser To extract a root element we need to include a few packages. Few packages are:

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;

Root element is extracted by

Element root = document.getDocumentElement()

Considering XMLRootElement annotation in an interface Using JAXB for Binding

@XmlRootElement
class SeaFoods {
@XmlAnyElement
public List<Fish> fish;
}
interface Fish{
void wings();
void eat();
...
}
@XmlRootElement
class Crab implements Fish { ... }
@XmlRootElement
class Prawn  implements Fish { ... }

XML document would look like this

<SeaFoods>
<Crab>hiii </Crab>
<Prawn> hello </Prawn>
</SeaFoods>

Customizing a root element with annotation

package educba
<java-type name="Banking">
<xml-root-element/>
<java-attributes>
<xml-element java-attribute="Branchname"/>
<xml-element java-attribute="PermanentAddress" name="Permanent-address"/>
<xml-element java-attribute="BCode" name="BCode"/>
</java-attributes>
</java-type>

To change a value in the root element

<Model name="sample.cre" version="v2.0" unit="a" count="0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

Android Element – Root element

Taking a new root element

RootElement root = new RootElement(samplename, "feed");
Element entry = root.getChild(samplename, "entry");
entry.getChild(samplename, "id").setEndTextElementListener(
new EndTextElementListener() {
public void end(String element1) {
System.out.println("content: " + element1);
}
});

Examples

Here we have a few examples of the root elements to go with for a valid XML document.

Example #1 – Simple XML code

store.xml

<?xml version="1.0" encoding="UTF-8"?>
<Dmartstore>
<shop List="Grocery">
<Cereals lang="en">Toor Dhal</Cereals>
<Brand>Sree Gold</Brand>
<year>2001</year>
<Quantity>150.00</Quantity>
</shop>
<shop List="Grocery">
<Shampoo lang="en">Loreal</Shampoo>
<Brand>USA</Brand>
<year>2005</year>
<Quantity>250.00</Quantity>
</shop>
<shop List="Grocery">
<Soaps lang="en">Lux</Soaps>
<Brand>India</Brand>
<year>2001</year>
<Quantity>210.00</Quantity>
</shop>
</Dmartstore>

Explanation:

In the above code Dmartstore is a root element along with the nested elements below. When we execute this code, we get the result as

Output:

XML root element output 1

XML root element output 2

Example #2 – Fetching a Root element Using java API

employee.xml:

<?xml version = "1.0" ?>
<Stock_db>
<Stocklist>
<StNo> SN345 </StNo>
<St_Name> Wipers </St_Name>
<St_E-mail> John_12@yahoo.com </St_E-mail>
</Stocklist>
<Stocklist>
<StNo> SN542 </StNo>
<St_Name> Glass </St_Name>
<St_E-mail> peeter_12@yahoo.com </St_E-mail>
</Stocklist>
<Stocklist>
<StNo> SN876 </StNo>
<St_Name> Tissue Papers </St_Name>
<St_E-mail> abrahm_18@yahoo.com </St_E-mail>
</Stocklist>
</Stock_db>

XmlExample.java:

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
public class XmlExample{
public static void main(String[] args) {
try{
BufferedReader bufR = new BufferedReader(
new InputStreamReader(System.in));
System.out.print("Load XML File: ");
String st1 = bufR.readLine();
File ff = new File(st1);
if (ff.exists()){
DocumentBuilderFactory Docf =
DocumentBuilderFactory.newInstance();
DocumentBuilder docb = Docf.newDocumentBuilder();
Document dc = docb.parse(st1);
Node nd = dc.getDocumentElement();
String root = nd.getNodeName();
System.out.println("Root Node: " + root);
}
else{
System.out.println("No File Exist!");
}
}
catch(Exception e1){}
}
}

Explanation:

This Code retrieves a root element from XML Files. XML files and Java files should be kept in the same directory. And the file is parsed using parse () function. To display a XML file getnode() method is used. So the output is given as:

Output:

XML root element output 3

Example #3

<?xml version = "1.0"?>
<Gadgets>
<Type no = "545">
<Mobile> Samsung</firstname>
<Tablet>IPhone</lastname>
<PC>Sony</nickname>
<Manufacturing>China</marks>
</Type>
<Type no = "413">
<Mobile> Nokia</firstname>
<Tablet> MAC</lastname>
<PC> Dell</nickname>
<Manufacturing>India</marks>
</Type>
<Type no = "871">
<Mobile> Redmi</firstname>
<Tablet>Cxxx</lastname>
<PC>Azure</nickname>
<Manufacturing>USA</marks>
</Type>
</Gadgets>

XmlExample.java:

import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
public class XmlExample {
public static void main(String[] args) {
try {
File f = new File("input.txt");
DocumentBuilderFactory dbF = DocumentBuilderFactory.newInstance();
DocumentBuilder dBui = dbF.newDocumentBuilder();
Document d = dBui.parse("employee.xml");
d.getDocumentElement().normalize();
System.out.println(" Display a Root element :" + d.getDocumentElement().getNodeName());
NodeList nl = d.getElementsByTagName("Type");
for (int t = 0; t < nl.getLength(); t++) {
Node nN = nl.item(t);
System.out.println("\nDisplaying an Element :" + nN.getNodeName());
if (nN.getNodeType() == Node.ELEMENT_NODE) {
Element eE = (Element) nN;
System.out.println("Type no : " + eE.getAttribute("no"));
System.out.println("Mobile : " + eE .getElementsByTagName("Mobile").item(0)
.getTextContent());
System.out.println("Tablet : "+ eE.getElementsByTagName("Tablet").item(0)
.getTextContent());
System.out.println("PC : "+ eE.getElementsByTagName("PC").item(0)
.getTextContent());
System.out.println("Manufacturing : "+ eE.getElementsByTagName("Manufacturing")
.item(0)
.getTextContent());
}
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

Explanation:

The following code gives the result as below for the input XML file

Output:

output 4

Example #4 – Changing name in the root element

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name = "cust")
@XmlType(propOrder = {"cid", "cname", "caddress"})
public class Billing {
private Integer cid;
private String cname;
private Address caddress;
@XmlElement
public Integer getI() {
return cid;
}
public void setI(Integer cid) {
this.cid = cid;
}
@XmlElement
public String getN() {
return cname;
}
public void setN(String cname) {
this.cname = cname;
}
@XmlElement
public Address getA() {
return caddress;
}
public void setA(caddress add) {
this.add = add;
}
}

Explanation:

The above code snippet changes class name into an assigned root element cust. Therefore, the output looks like this:

Output:

output 5

Conclusion

This article describes how to use XmlRootElement in the java platform. This can be done using the Element Declaration. To handle multiple root elements in XSD @XmlRootElement annotation is used.

Recommended Articles

This is a guide to the XML root element. Here we discuss how to use XmlRootElement in java platform along with the examples and outputs. You may also have a look at the following articles to learn more –

  1. XML Mapping
  2. XML HttpRequest 
  3. XML Encoding
  4. XML Attributes
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more