EDUCBA

EDUCBA

MENUMENU
  • Explore
    • Lifetime Membership
    • All in One Bundles
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign up
Home Software Development Software Development Tutorials XML Tutorial XML root element

XML root element

Updated April 3, 2023

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.

ADVERTISEMENT
Popular Course in this category
XML Course Bundle - 11 Courses in 1

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

The XML Schema Definition defines as:

<?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> [email protected] </St_E-mail>
</Stocklist>
<Stocklist>
<StNo> SN542 </StNo>
<St_Name> Glass </St_Name>
<St_E-mail> [email protected] </St_E-mail>
</Stocklist>
<Stocklist>
<StNo> SN876 </StNo>
<St_Name> Tissue Papers </St_Name>
<St_E-mail> [email protected] </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
ADVERTISEMENT
C++ PROGRAMMING Course Bundle - 9 Courses in 1 | 5 Mock Tests
40+ Hour of HD Videos
9 Courses
5 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
ASP.NET Course Bundle - 28 Courses in 1 | 5 Mock Tests
123+ Hours of HD Videos
28 Courses
5 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
SQL Course Bundle - 51 Courses in 1 | 6 Mock Tests
205+ Hours of HD Videos
51 Courses
6 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
SOFTWARE TESTING Course Bundle - 13 Courses in 1
53+ Hour of HD Videos
13 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
Primary Sidebar
Footer
Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
  • Blog as Guest
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

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

EDUCBA

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

Let’s Get Started

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

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA

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

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

Forgot Password?

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

🚀 Cyber Monday Reloaded Price Drop! All in One Universal Bundle (3700+ Courses) @ 🎁 90% OFF - Ends in ENROLL NOW