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 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 Element

By Priya PedamkarPriya Pedamkar

XML Element

Definition of XML Element

An XML element is defined as a user-defined container used to store text elements and attributes. It consists of a start tag and end tag. The main Objective of the element is to describe data. The start tag may include attributes and should be enclosed within double-quotes. The XML element may have another element in it as its content like nested. XML document is considered to be an ordered tree and every node of the tree is an element and every document should have a top-level element as the root element.

Syntax:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

To write an element in an XML document we need to give the following syntax.

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,198 ratings)

<element-name attribute1 >
.// Content code
</element-name>

So here element name is the name of the element given for the specific document. The same name should be given at the start and the end tag also cases should match the end tag.

Next is the Attribute name which defines the property of an element is defined separately next to the element with White Spaces.

How does Element Work in XML?

In XML document Element is the basic unit in the document where the child elements are given under the parent element, which may be sometimes a child element. The Root element which is considered at the top of the structure is the main element where all the elements are contained in them. There are two forms, one is non-empty elements and the other one is Empty elements.

  • Non-empty Elements: This is also called a Container element where the content of the text is placed between a start tag and end tag.
  • Standalone Element: It is an empty tag with no content in them and given by a forward slash “/”. And it is declared as:

<name attribute 1 attribute2…/>

Example:

<name firstname=” hi”>

There is no specific procedure to work on it. It works well with several properties associated with it: They are:

  • Tag
  • Attributes
  • A text String
  • A sequence of child elements.

The Structure of the element is defined in DTD using the following format:

<!ELEMENT element-name (content)>
////
<!ELEMENT element-name types>  // types like PCDATA

 XML elements have few Rules to go with:

  • An element name can have specific alphanumeric Characters also along with hyphen (-), under-score (_), and period (.).
  • Names Here are case sensitive. For example, Location, locations, and LOCATION are different names.
  • Should have identical names on start tag and end tag.
  • An element which is said to be a container in documents has text or nested elements within it.

An XML element goes well with attributes for identifying an element. The attribute values are quoted as shown below:

<patient id="1">
<details>
<firstname>Olaro</firstname>
<marital>Married</marital>
<location>Texas</location>
</ details >
< patient >

There is a difference between Element and attributes. Let us see the following sample to make clear.

<library id="01">   // the way Attributes defined
...
< library >
< library >          // the way Elements are defined
<id>01</id>
< library >

In Java XMLElement class is associated with Set Attribute () method which seeks parent element default.  Even though the element has content types like mixed, simple, empty, it is advisable to prefer mixed content. A namespace is a concept used here specified with a prefix.

Examples of XML Element

Here are the few examples of valid XML Element in Document.

Example #1

Simple XML document showing parent, child elements.

store.xml

<?xml version="1.0" encoding="UTF-8"?>
<sparstore>
<shop category="Gadgets">
<Model lang="en">GT4352</Model>
<Company>Samsung</Company>
<year>2020</year>
<ownat>120.00</ownat>
</shop>
<shop category="Gadgets">
<Model lang="en">GH5648</Model>
<Company>Redmi</Company>
<year>2018</year>
<ownat>110.00</ownat>
</shop>
<shop category="Gadgets">
<Model lang="en">AMT234</Model>
<Company>Ziami</Company>
<year>2019</year>
<ownat>130.00</ownat>
</shop>
</sparstore>

Explanation: In the above code superstore is a root element with a nested element named shop with an attribute “category. When we execute this in a browser, we could see the following output.

Output:

XML Element-1.1

Example #2

XML Name with NameSpace

node.xml

<?xml version="1.0" encoding="UTF-8"?>
<parent>
<def:ping xmlns:def="http://www.shopmeal.com">
<time>07/09/2020 8:01:00</time>
<request>GET /hello.html 200</request>
</def:ping>
<ct:ping xmlns:ct="http://www.retailwal.com">
<Orderitem>handbags</Orderitem>>
<Orderitem>>gadgets</Orderitem>>
<Orderitem>>clothes</Orderitem>>
</ct:ping>
<ct:ping xmlns:ct="http://www.nosfeagian.com">
<time>7/12/2019 7:05:43</time>
<request>GET /images/label.gif 304</request>
</ct:ping></parent>

Explanation: In the above code, we have used ‘def’ a namespace property with a prefix and also a URI.

Output:

XML Element-1.2

Example #3

Extracting XML Elements using Java code.

new.xml

<?xml version="1.0"?>
<shops>
<supermarket>
<sid>201</sid>
<sname> sparc</sname>
<product> grocery</product>
<branch> two</branch>
<location> new york</location>
</supermarket>
<supermarket>
<sid>540</sid>
<sname> big basket</sname>
<product> grocery</product>
<branch> seven</branch>
<location>India</location>
</supermarket>
<supermarket>
<sid>301</sid>
<sname> Wallmart</sname>
<product> grocery</product>
<branch> fifteen</branch>
<location> France</location>
</supermarket>
</shops>

Read.java

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;
import java.io.File;
public class Read
{
public static void main(String argv[])
{
try
{
File file = new File("C:\\Program Files\\Java\\jdk-13.0.1\\par\\new.xml");
DocumentBuilderFactory docb = DocumentBuilderFactory.newInstance();
DocumentBuilder dbu = docb.newDocumentBuilder();
Document dt = dbu.parse(file);
dt.getDocumentElement().normalize();
System.out.println("Root: " + dt.getDocumentElement().getNodeName());
NodeList nd = dt.getElementsByTagName("supermarket");
for (int i = 0; i < nd.getLength(); i++)
{
Node node = nd.item(i);
System.out.println("\nNode Name :" + node.getNodeName());
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element el = (Element) node;
System.out.println("supermarket sid: "+ el.getElementsByTagName("sid").item(0).getTextContent());
System.out.println("sname: "+  el.getElementsByTagName("sname").item(0).getTextContent());
System.out.println("product: "+  el.getElementsByTagName("product").item(0).getTextContent());
System.out.println("branch: "+  el.getElementsByTagName("branch").item(0).getTextContent());
System.out.println("location: "+ el.getElementsByTagName("location").item(0).getTextContent());
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Explanation: Using the get Element method we can extract an XML file in java code using factory classes. So in the below output, we could see an element with a value.

Output:

Output-1.3

Example #4

Counting No. of Elements.

bank.xml

<Banking>
<bank id="123">
<foreName>Giana</foreName>
<SurName>Amreal</SurName>
<HomeAddress>USA</HomeAddress>
</bank>
<bank id="456">
<foreName>Chris</foreName>
<SurName>Houtson</SurName>
<HomeAddress>Sweden</HomeAddress>
</bank>
<bank id="654">
<foreName>Dallni</foreName>
<SurName>Furaq</SurName>
<HomeAddress>Australia</HomeAddress>
</bank>
</Banking>

 Number.java

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.*;
public class Number {
private static final String xmlfilepath = "C:\\Program Files\\Java\\jdk-13.0.1\\par\\Bank.xml";
public static void main(String argv[]) {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(xmlfilepath);
NodeList nl = doc.getElementsByTagName("bank");
System.out.println("Number of elements with bank : " + nl.getLength());
} catch (ParserConfigurationException pex) {
pex.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
} catch (SAXException se) {
se.printStackTrace();
}
}
}

Explanation: With the count initializing of an element, the parser counts the number of elements in the XML path.

Output:

Output-1.4

Conclusion

XML element being main Objects in XML document plays a vital role in the Coding process with java or python as they parse a root element to child element using DOM, and easier part is there are no fixed rules so it is easy for the learners. So, in this article, we have covered the basics and also done with their working with an example.

Recommended Articles

This is a guide to XML Element. Here we also discuss the definition and how does element work in xml along with different examples and its code implementation. You may also have a look at the following articles to learn more –

  1. XML Namespaces
  2. XML Comments
  3. XML Technologies
  4. XML Encoding
Popular Course in this category
XML Training (5 Courses, 6+ Projects)
  5 Online Courses |  6 Hands-n Projects |  40+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
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