0% found this document useful (0 votes)
25 views80 pages

Unit 3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views80 pages

Unit 3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Unit-3

XML, JSON
By
Dr. Chilukala Mahender Reddy
Content:
• XML: Syntax of XML,
• document structure,
• document type definition,
• namespaces,
• XML schemas,
• document object model,
• presenting XML using CSS, XSLT, XPath, XQuery, FLOWR.
• JSON: Features, JSON vs. XML,
• JSON Data Types,
• JSON Objects,
• JSON Arrays,
• JSON HTML.
What is XML?:

• XML is a software- and hardware-independent tool for storing and transporting


data.
• XML stands for eXtensible Markup Language
• XML is a markup language much like HTML
• XML was designed to store and transport data
• XML was designed to be self-descriptive
• XML is a W3C Recommendation
The Difference Between XML and HTML:

• XML and HTML were designed with different goals:


• XML was designed to carry data - with a focus on what data is
• HTML was designed to display data – with a focus on how data looks
• XML tags are not predefined like HTML tags are
XML Does Not Use Predefined Tags:

• The XML language has no predefined tags. <note>


• The tags in the example (like <to> and <from>) <to>Tove</to>
are not defined in any XML standard. These tags <from>Jani</from>
<heading>Reminder</heading>
are "invented" by the author of the XML <body>Don't forget me this
document. weekend!</body>
</note>
• HTML works with predefined tags like <p>,
<h1>, <table>, etc.
• With XML, the author must define both the tags
and the document structure.
The Syntax of XML
• Levels of syntax
• General low-level syntax: Well-formed documents conform to basic XML
rules
• Syntactic level: Valid documents are well-formed and also conform to a
schema that defines details of the allowed content
• Well-formed XML documents
• All begin tags have a matching end tag
• Empty tags
• If a begin tag is inside an element, the matching end tag is also
• There is one root tag that contains all the other tags in a document
• Attributes must have a value assigned, the value must be quoted
• The characters <, >, & can only appear with their special meaning
XML Document Structure
• XML documents create a hierarchical structure that looks like a tree so it is known
as XML Tree that starts at "the root" and branches to "the leaves“.
• XML documents must contain a root element. This element is "the parent" of all
other elements.
• The elements in an XML document form a document tree. The tree starts at the
root and branches to the lowest level of the tree.
• All elements can have sub-elements (child elements).
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
• The terms parent, child, and sibling are used to describe the relationships between
elements. Parent elements have children. Children on the same level are called
siblings (brothers or sisters).
XML Attributes:
• XML elements can have attributes. By the use of attributes, we can add
information about the element.
• XML attributes enhance the properties of the elements.
<book publisher="Tata McGraw Hill"></book>
• Metadata should be stored as an attribute and data should be stored as an element.
<book>
<book category="computer">
<author> A & B </author>
</book>
• Data can be stored in attributes or in child elements. But there are some limitations
in using attributes, over child elements.
Why should we avoid XML attributes:

• Attributes cannot contain multiple values but child elements can have multiple
values.
• Attributes cannot contain tree structure but child elements can.
• Attributes are not easily expandable. If you want to change an attribute’s values in
the future, it may be complicated.
• Attributes cannot describe structure but child elements can.
• Attributes are more difficult to be manipulated by program code.
• Attributes values are not easy to test against a DTD, which is used to define the
legal elements of an XML document.
XML Comments:
• XML comments are just like HTML comments. We know that the comments are
used to make codes more understandable to other developers.
• XML Comments add notes or lines for understanding the purpose of an XML
code. Although XML is known as self-describing data sometimes XML comments
are necessary.
• Syntax
• An XML comment should be written as:
• <!-- Write your comment-->
• Rules for adding XML comments
• Don't use a comment before an XML declaration.
• You can use a comment anywhere in XML document except within the
attribute value.
• Don't nest a comment inside the other comment.
XML Tree Structure:
<?xml version="1.0"?>
<college>
<student>
<firstname>Mahender</firstname>
<lastname>Reddy</lastname>
<contact>09990449935</contact>
<email>[email protected]</email>
<address>
<city>Ghaziabad</city>
<state>Uttar Pradesh</state>
<pin>201007</pin>
</address>
</student>
</college>
Rules for well formed XML:
• It must begin with the XML declaration.
• It must have one unique root element.
• All start tags of XML documents must match end tags.
• XML tags are case-sensitive.
• All elements must be closed.
• All elements must be properly nested.
• All attribute values must be quoted.
• XML entities must be used for special characters.
Document Type Definitions(DTD):
What is DTD
• DTD stands for Document Type Definition. It defines the legal building blocks of
an XML document. It is used to define document structure with a list of legal
elements and attributes.
Purpose of DTD
• Its main purpose is to define the structure of an XML document. It contains a list
of legal elements and defines the structure with the help of them.
Checking Validation
• Before proceeding with XML DTD, you must check the validation. An XML
document is called "well-formed" if it contains the correct syntax.
• A well-formed and valid XML document has been validated against DTD.
Valid and well-formed XML document with DTD
employee.xml
<?xml version="1.0"?>
<!DOCTYPE employee SYSTEM "employee.dtd">
<employee>
<firstname>vimal</firstname>
<lastname>jaiswal</lastname>
<email>[email protected]</email>
</employee>
• In the above example, the DOCTYPE declaration refers to an external DTD file.
The content of the file is shown in below paragraph.
employee.dtd
<!ELEMENT employee (firstname,lastname,email)>
<!ELEMENT firstname (#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT email (#PCDATA)>
Description of DTD:
• <!DOCTYPE employee: It defines that the root element of the document is an employee.
• <!ELEMENT employee: It defines that the employee element contains 3 elements "firstname,
lastname and email".
• <!ELEMENT firstname: It defines that the firstname element is #PCDATA typed. (parse-able data
type).
• <!ELEMENT lastname: It defines that the lastname element is #PCDATA typed. (parse-able data
type).
• <!ELEMENT email: It defines that the email element is #PCDATA typed. (parse-able data type).
Note: PCDATA
• PCDATA means parsed character data.
• Think of character data as the text found between the start tag and the end tag of an XML element.
• PCDATA is text that WILL be parsed by a parser. The text will be examined by the parser for
entities and markup.
• Tags inside the text will be treated as markup and entities will be expanded.
• However, parsed character data should not contain any &, <, or > characters; these need to be
represented by the &amp; &lt; and &gt; entities, respectively.
Declaring Entities
• A doctype declaration can also define special strings that can be used in the XML
file.
• An entity has three parts:
1. An ampersand (&)
2. An entity name
3. A semicolon (;)
• Syntax to declare entity:
• <!ENTITY entity-name "entity-value">
• Let's see a code to define the ENTITY in doctype declaration.
• author.xml
<?xml version="1.0" standalone="yes" ?>
<!DOCTYPE author [
<!ELEMENT author (#PCDATA)>
<!ENTITY sj "Sonoo Jaiswal"> ]>
<author>&sj;</author>
Internal and External DTDs
• A document type declaration can either contain declarations directly or refer to
another file
• Internal
• <!DOCTYPE root-element [
declarations
]>
• External file
• <!DOCTYPE root-name SYSTEM “file-name”>
• A public identifier can also be specified, that would be mapped to a system
identifier by the processing system
Namespaces
• XML Namespace is used to avoid element name conflict in XML document.
• An XML namespace is declared using the reserved XML attribute. This attribute
name must be started with "xmlns".
• Let's see the XML namespace syntax:
• <element xmlns:name = "URL">
• Here, the namespace starts with the keyword "xmlns". The word name is a
namespace prefix. The URL is a namespace identifier.
<?xml version="1.0" encoding="UTF-8"?>
<cont:contact xmlns:cont="http://sssit.org/contact-us">
<cont:name>Vimal Jaiswal</cont:name>
<cont:company>SSSIT.org</cont:company>
<cont:phone>(0120) 425-6464</cont:phone>
</cont:contact>
• Namespace Prefix: cont
• Namespace Identifier: http://sssit.org/contact-us
• It specifies that the element name and attribute names with cont prefix belong to
http://sssit.org/contact-us namespace.
• In XML, element names are defined by the developer so there is a chance to
conflict in the name of the elements. To avoid these types of conflict we use XML
Namespaces. We can say that XML Namespaces provides a method to avoid
element name conflict.
• Generally these conflict occurs when we try to mix XML documents from
different XML applications.
<table>
<tr>
<td>Aries</td>
<td>Bingo</td>
</tr>
</table>

<table>
<name>Computer table</name>
<width>80</width>
<length>120</length>
</table>

If you add both XML fragments together, there would be a name conflict because
both have <table> elements. Although they have different names and meanings.
You can easily avoid the XML namespace by using a name prefix.
<h:table>
<h:tr>
<h:td>Aries</h:td>
<h:td>Bingo</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>Computer table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
• You can use xmlns attribute to define a namespace with the following syntax:
<root>
<h:table xmlns:h="http://www.abc.com/TR/html4/">
<h:tr>
<h:td>Aries</h:td>
<h:td>Bingo</h:td>
</h:tr>
</h:table>

<f:table xmlns:f="http://www.xyz.com/furniture">
<f:name>Computer table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>

In the above example, the <table> element defines a namespace and when a namespace is defined for an element, the
child elements with the same prefixes are associated with the same namespace.
<root xmlns:h="http://www.abc.com/TR/html4/"
xmlns:f="http://www.xyz.com/furniture">
<h:table>
<h:tr>
<h:td>Aries</h:td>
<h:td>Bingo</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>Computer table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
XML Schemas
What is XML schema?
XML schema is a language that is used for expressing constraints about XML
documents. There are so many schema languages that are used nowadays for
example Relax- NG and XSD (XML schema definition).
An XML schema is used to define the structure of an XML document. It is like DTD
but provides more control over XML structure.
Checking Validation
An XML document is called "well-formed" if it contains the correct syntax. A well-
formed and valid XML document has been validated against Schema.
employee.xsd example.xml
<?xml version="1.0"?> <?xml version="1.0"?>
<xs:schema <employee
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="http://www.javatpoint.com"
targetNamespace="http://www.javatpoint.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
xmlns="http://www.javatpoint.com" instance"
elementFormDefault="qualified"> xsi:schemaLocation=" http://www.javatpoint.com
<xs:element name="employee"> employee.xsd">
<xs:complexType>
<xs:sequence> <firstname>vimal</firstname>

<xs:element name="firstname" type="xs:string"/> <lastname>jaiswal</lastname>


<xs:element name="lastname" type="xs:string"/> <email>[email protected]</email>

<xs:element name="email" type="xs:string"/> </employee>

</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Description of XML Schema:

• <xs:element name="employee"> : It defines the element name employee.


• <xs:complexType>: It defines that the element 'employee' is a complex type.
• <xs:sequence> : It defines that the complex type is a sequence of elements.
• <xs:element name="firstname" type="xs:string"/>: It defines that the element
'firstname' is of string/text type.
• <xs:element name="lastname" type="xs:string"/>: It defines that the element
'lastname' is of string/text type.
• <xs:element name="email" type="xs:string"/>: It defines that the element
'email' is of string/text type.
An Overview of Data Types
• Data types are of two kinds
• Simple data types with string content
• Complex data types with elements, attributes and string content
• Predefined types
• Primitive
• Derived
• Restrictions
• Facets
• Anonymous and named types
Simple Types
• Named types can be used to give the type of
• an attribute (which must be simple) or
• an element (which may be simple or complex)
• Elements or attributes with simple type may have default values specified
• New simple types can be defined by restriction of base types
• Facet maxLength
• Facet precision
<xs:element name="age">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="0"/>
<xs:maxInclusive value="120"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
Complex Types
• A complex element is an XML element that contains other elements
and/or attributes.
• There are four kinds of complex elements:
• empty elements
• elements that contain only other elements
• elements that contain only text
• elements that contain both other elements and text
Note: Each of these elements may contain attributes as well!
• A complex XML element, "product", which is empty:
<product pid="1345"/>
• A complex XML element, "employee", which contains only other elements:
<employee>
<firstname>John</firstname>
<lastname>Smith</lastname>
</employee>
• A complex XML element, "food", which contains only text:
<food type="dessert">Ice cream</food>
• A complex XML element, "description", which contains both elements and text:
<description>
It happened on <date lang="norwegian">03.03.99</date> ....
</description>
XML DOM:
What is XML DOM
• DOM is an acronym that stands for Document Object Model. It defines a standard
way to access and manipulate documents. The Document Object Model (DOM) is
a programming API for HTML and XML documents. It defines the logical
structure of documents and the way a document is accessed and manipulated.
• As a W3C specification, one important objective for the Document Object Model
is to provide a standard programming interface that can be used in a wide variety
of environments and applications. The Document Object Model can be used with
any programming language.
• XML DOM defines a standard way to access and manipulate XML documents.
What does XML DOM?:

• The XML DOM makes a tree-structure view for an XML document.


• We can access all elements through the DOM tree.
• We can modify or delete their content and also create new elements. The elements
and their content (text and attributes) are all known as nodes.
<TABLE>
<ROWS>
<TR>
<TD>A</TD>
<TD>B</TD>
</TR>
<TR>
<TD>C</TD>
<TD>D</TD>
</TR>
</ROWS>
</TABLE>
XML DOM Example: Load XML File:
• Let's take an example to show how an XML document ("note.xml") is parsed into
an XML DOM object.
• This example parses an XML document (note.xml) into an XML DOM object and
extracts information from it with JavaScript.
• note.xml
<?xml version="1.0"?>
<note>
<to>[email protected]</to>
<from>[email protected]</from>
<body>Hello XML DOM</body>
</note>
<!DOCTYPE html>
<html>
<body>
<h1>Important Note</h1>
<div>
<b>To:</b> <span id="to"></span><br>
document.getElementById("message").innerHTML=
<b>From:</b> <span id="from"></span><br>
xmlDoc.getElementsByTagName("body")[0].childNodes
<b>Message:</b> <span id="message"></span> [0].nodeValue;
</div>
</script>
<script>
</body>
xmlhttp.open("GET","note.xml",false);
xmlhttp.send(); </html>
xmlDoc=xmlhttp.responseXML;
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
XML DOM Example: Load XML String
<!DOCTYPE html> parser=new DOMParser();
<html> xmlDoc=parser.parseFromString(txt,"text/xml"); }
<body> else{ // Internet Explorer
<h1>Important Note2</h1> xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
<div> xmlDoc.async=false;
<b>To:</b> <span id="to"></span><br> xmlDoc.loadXML(txt); }
<b>From:</b> <span id="from"></span><br> document.getElementById("to").innerHTML=
<b>Message:</b> <span id="message"></span> xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
</div> document.getElementById("from").innerHTML=
<script> xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
txt1="<note>"; document.getElementById("message").innerHTML=
txt2="<to>Sania Mirza</to>"; xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
txt3="<from>Serena William</from>";
</script>
txt4="<body>Don't forget me this weekend!</body>";
</body>
txt5="</note>";
</html>
txt=txt1+txt2+txt3+txt4+txt5;
if (window.DOMParser) {
Displaying XML Using CSS:
• An XML file can be displayed using two ways. These are as follows:-
1. Cascading Style Sheet
2. Extensible Stylesheet Language Transformation
• CSS can be used to display the contents of the XML document in a clear and
precise manner. It gives the design and style to the whole XML document.
• Basic steps in defining a CSS style sheet for XML :
• Define the style rules for the text elements such as font-size, color, font-weight,
etc.
• Define each element either as a block, inline, or list element, using the display
property of CSS.
• Identify the titles and bold them.
• Linking XML with CSS :
To display the XML file using CSS, link the XML file with CSS. Below is the
syntax for linking the XML file with CSS:
<?xml-stylesheet type="text/css" href="name_of_css_file.css"?>
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="Rule.css"?>
<books>
<heading>Welcome To GeeksforGeeks </heading>
<book>
<title>Title -: Web Programming</title>
<author>Author -: Chrisbates</author>
<publisher>Publisher -: Wiley</publisher>
<edition>Edition -: 3</edition>
<price> Price -: 300</price>
</book>
<book>
<title>Title -: Internet world-wide-web</title>
<author>Author -: Ditel</author>
<publisher>Publisher -: Pearson</publisher>
<edition>Edition -: 3</edition>
<price>Price -: 400</price>
</book>
</books>
Rule.css
books {
color: white;
background-color : gray;
width: 100%;
}
heading {
color: green;
font-size : 40px;
background-color : powderblue;
}
heading, title, author, publisher, edition, price {
display : block;
}
title {
font-size : 25px;
font-weight : bold;
}
XSLT Style Sheets
• XSL stands for EXtensible Stylesheet Language. It is a styling language for XML
just like CSS is a styling language for HTML.
• XSLT is for the Transformation of XML documents to other formats.
• XSLT stands for XSL Transformation. It is used to transform XML documents
into other formats (like transforming XML into HTML).
What is XSL?
• In HTML documents, tags are predefined but in XML documents, tags are not
predefined. World Wide Web Consortium (W3C) developed XSL to understand
and style an XML document, which can act as an XML-based Stylesheet
Language.
• An XSL document specifies how a browser should render an XML document.
Main parts of the XSL Document
• XSLT: It is a language for transforming XML documents into various other types
of documents.
• XPath: It is a language for navigating in XML documents.
• XQuery: It is a language for querying XML documents.
• XSL-FO: It is a language for formatting XML documents.
XSLT Syntax
• Let's take an example to take a sample XML file and transform it into a well-
formatted HTML document.
• See this example:
• Create an XML file named employee.xml,
• Create an XSL file named employee.xsl,
<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "employee.xsl"?>
<class>
...
</class>
Employee.xml </employee>
<?xml version = "1.0"?> <employee id = "056">
<?xml-stylesheet type = "text/xsl" href = "employee.xsl"?> <firstname>Peter</firstname>
<class> <lastname>Symon</lastname>
<employee id = "001"> <nickname>John</nickname>
<firstname>Aryan</firstname> <salary>10000</salary>
<lastname>Gupta</lastname> </employee>
<nickname>Raju</nickname> </class>
<salary>30000</salary>
</employee>
<employee id = "024">
<firstname>Sara</firstname>
<lastname>Khan</lastname>
<nickname>Zoya</nickname>
<salary>25000</salary>
Employee.xsl <xsl:for-each select="class/employee">
<?xml version = "1.0"?> <tr>
<xsl:stylesheet version = "1.0" <td>
xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"> <xsl:value-of select = "@id"/>
<xsl:output method="text"/> </td>
<xsl:template match = "/"> <td><xsl:value-of select = "firstname"/></td>
<html> <td><xsl:value-of select = "lastname"/></td>
<body> <td><xsl:value-of select = "nickname"/></td>
<h2>Employee</h2> <td><xsl:value-of select = "salary"/></td>
<table border = "1"> </tr>
<tr bgcolor = "#9acd32"> </xsl:for-each>
<th>ID</th> </table>
<th>First Name</th> </body>
<th>Last Name</th> </html>
<th>Nick Name</th> </xsl:template>
<th>Salary</th> </xsl:stylesheet>
</tr>
XSLT <xsl:value-of> Element
• The XSLT <xsl:value-of> element is used to extract the value of the selected node.
It puts the value of the selected node as per Xpath expression, as text.
<xsl:value-of
select = Expression
disable-output-escaping = “yes” | “no”>
</xsl:value-of>
Select: It specifies the Xpath expression to be evaluated in the current context.
Disable-output-escaping: Default-”no”. If “yes”, output text will not escape XML
characters from the text.
XSLT <xsl:for-each> Element
• The XSLT <xsl:for-each> element is used to apply a template repeatedly for each
node.
<xsl:for-each
select = Expression>
</xsl:for-each>
• Select: Xpath Expression to be evaluated in the current context to determine the
set of nodes to be iterated.
XSLT <xsl:sort> Element
• The XSLT <xsl:sort> element is used to specify a sort criteria on the nodes. It
displays the output in sorted form.
• The <xml:sort> element is added inside the <xsl:for-each> element in the XSL
file, to sort the output.
<xsl:sort
select = string-expression
lang = { nmtoken }
data-type = { "text" | "number" | QName }
order = { "ascending" | "descending" }
case-order = { "upper-first" | "lower-first" } >
</xsl:sort> Index Name Description
1) select It is used for sorting key of the node.
2) lang It specifies language alphabet used to determine sort order.
3) data-type It specifies data-type of the text.
4) order It is used to specify the sorting order. By default sorting order is ascending order.

5) case-order It is used to specify sorting order of string by capitalization. Default is "upper-first".


XSLT <xsl:if> Element
• The XSLT <xsl:if> element is used to specify a conditional test against the content
of the XML file.
<xsl:if test="expression">
...some output if the expression is true...
</xsl:if>
• test: It specifies a condition in XML data to test.
XSLT <xsl:choose> Element
• The XSLT <xsl:choose> element is used to specify a multiple conditional test
against the content of nodes with the <xsl:otherwise> and <xsl:when> elements.
<xsl:choose>
<xsl:when test="expression">
... some output ...
</xsl:when>
<xsl:otherwise>
... some output ....
</xsl:otherwise>
</xsl:choose>
• test: It specifies a condition in xml data to test.
XSLT <xsl:key> Element
• The XSLT element is used to specify a named name-value pair assigned to a
specific element in an XML document. This key is used with the key() function in
XPath expressions to access the assigned elements in an XML document.
<xsl:key
name = QName
match = Pattern
use = Expression>
</xsl:key>
Index Name Description
1) Name It specifies the name of the key to be used.
2) Match It specifies that the pattern must be matched to a node that
holds this key.
3) Use It specifies XPath expression to identify the value of the nodes of
xml document.
XSLT <xsl:message> Element
• The XSLT <xsl:message> element is used to display the error message and help to
debug the XSLT processing. It is similar to JavaScript alerts. This element buffers
a message to the XSLT processor which terminates the processing and sends a
message to the caller application to show an error message.
<xsl:message
terminate = "yes" | "no">
</xsl:message>
• Terminate: When the terminate attribute is set to "yes", the content of the element
is displayed as part of the system-level error message, and the transformation
terminates. When it is set to "no", the transformation proceeds, ignoring the error
message. By default value is no.
XSLT <xsl:apply-template> Element
• The XSLT <xsl:apply-template> element is used to tell XSLT processor to find the
appropriate template to apply according to the type and context of each selected
node.
<xsl:apply-template
select = Expression
mode = QName>
</xsl:apply-template>
Index Name Description
1) select It is used to process nodes selected by XPath expressions from the
list of all nodes and its children.
2) mode It is used to allow an element as specified by its qualified names to
be processed multiple times, each time producing a different
result.
XSLT <xsl:import> Element
• The XSLT <xsl:import> element is used to import the content of one stylesheet to
another stylesheet. The importing stylesheet has higher precedence over the
imported stylesheet.
<xsl:import href = "uri">
</xsl:import>
• href: It is used to provide the path of the XSLT stylesheet to be imported.
XPath:
XPath (XML Path Language) is a query language used to navigate and query XML
documents. It provides a way to locate and process elements within an XML
document by defining paths through the document's structure.
Syntax:
• XPath expressions are written as strings and use a syntax similar to file paths.
• Basic syntax: /root/element[@attribute='value']
Nodes:
• XPath operates on the concept of nodes, which can be elements, attributes, text,
and more.
• The main types of nodes are element nodes, attribute nodes, text nodes, and
namespace nodes.
Location Path:
• A fundamental concept in XPath is the location path, which is a series of steps
used to navigate through the XML document.
• Example: /bookstore/book/title
Axes:
• Axes define relationships between elements, such as parent, child, or sibling
relationships.
• Common axes include child (/), parent (..), descendant (//), and attribute (@).
Predicates:
• Predicates filter nodes based on certain conditions.
• Example: /bookstore/book[price>30] selects books with a price greater than 30.
Wildcards:
• Wildcards can be used to select multiple elements without specifying their exact
names.
• Example: /bookstore/* selects all child elements of the bookstore element.
Functions:
• XPath provides a variety of functions for string manipulation, numeric operations,
and more.
• Example: /bookstore/book[position()=1] selects the first book element.
Selecting Attributes:
• Attributes can be selected using the @ symbol followed by the attribute name.
• Example: /bookstore/book/@category selects the category attribute of the book
element.
XPath in XML Document:
• XPath expressions are often used in conjunction with XML documents, either in
programming languages or tools like XSLT.
Namespace Prefixes:
• When working with XML namespaces, XPath allows you to use namespace
prefixes to identify elements.
• Example: /ns:bookstore/ns:book where ns is the namespace prefix.
XQuery:
What is XQuery?
• XQuery is a functional query language used to retrieve information stored in XML
format. It is the same as for XML what SQL is for databases. It was designed to
query XML data.
• XQuery is built on XPath expressions. It is a W3C recommendation which is
supported by all major databases.
• The definition of XQuery given by its official documentation is as follows:
• “XQuery is a standardized language for combining documents, databases, Web
pages, and almost anything else. It is very widely implemented. It is powerful and
easy to learn. XQuery is replacing proprietary middleware languages and Web
Application development languages.
<?xml version="1.0" encoding="UTF-8"?> <course category="C">
<courses> <title lang="en">Learn C in 2 Months.</title>
<course category="JAVA"> <trainer>Ramesh Kumar</trainer>
<title lang="en">Learn Java in 3 Months.</title> <year>2014</year>
<trainer>Sonoo Jaiswal</trainer> <fees>3000.00</fees>
<year>2008</year> </course>
<fees>10000.00</fees> <course category="XML">
</course> <title lang="en">Learn XML in 2 Months.</title>
<course category="Dot Net"> <trainer>Ajeet Kumar</trainer>
<title lang="en">Learn Dot Net in 3 Months.</title> <year>2015</year>
<fees>4000.00</fees>
<trainer>Vicky Kaushal</trainer>
</course>
<year>2008</year> </courses>
<fees>10000.00</fees>
</course>
for $x in doc("courses.xml")/courses/course
where $x/fees>5000
return $x/title
XQuery FLWOR:

• FLWOR is an acronym that stands for "For, Let, Where, Order by, Return".
• For - It is used to select a sequence of nodes.
• Let - It is used to bind a sequence to a variable.
• Where - It is used to filter the nodes.
• Order by - It is used to sort the nodes.
• Return - It is used to specify what to return (gets evaluated once for every node).
<?xml version="1.0" encoding="UTF-8"?> <course category="C">
<courses> <title lang="en">Learn C in 2 Months.</title>
<course category="JAVA"> <trainer>Ramesh Kumar</trainer>
<title lang="en">Learn Java in 3 Months.</title> <year>2014</year>
<trainer>Sonoo Jaiswal</trainer> <fees>3000.00</fees>
<year>2008</year> </course>
<fees>10000.00</fees> <course category="XML">
</course> <title lang="en">Learn XML in 2 Months.</title>
<course category="Dot Net"> <trainer>Ajeet Kumar</trainer>
<title lang="en">Learn Dot Net in 3 Months.</title> <year>2015</year>
<fees>4000.00</fees>
<trainer>Vicky Kaushal</trainer>
</course>
<year>2008</year> </courses>
<fees>10000.00</fees>
</course>
let $courses := (doc("courses.xml")/courses/course)
return <results>
{
for $x in $courses
where $x/fees>2000
order by $x/fees
return $x/title
}
</results>
JSON:
What is JSON?
• JSON stands for JavaScript Object Notation
• JSON is a lightweight data interchange format
• JSON is a plain text written in JavaScript object notation
• JSON is used to send data between computers
• JSON is language independent *
Why Use JSON?
• The JSON format is syntactically similar to the code for creating JavaScript objects.
Because of this, a JavaScript program can easily convert JSON data into JavaScript objects.
• Since the format is text only, JSON data can easily be sent between computers, and used by
any programming language.
• JavaScript has a built-in function for converting JSON strings into JavaScript objects:
JSON.parse()
• JavaScript also has a built-in function for converting an object into a JSON string:
JSON.stringify()
JSON Example
• This example is a JSON string:
'{"name":"John", "age":30, "car":null}'
• It defines an object with 3 properties:
• name
• age
• car
• Each property has a value.
• If you parse the JSON string with a JavaScript program, you can access the data as
an object:
let personName = obj.name;
let personAge = obj.age;
JSON vs XML
JSON is Like XML Because
• Both JSON and XML are "self-describing" (human readable)
• Both JSON and XML are hierarchical (values within values)
• Both JSON and XML can be parsed and used by lots of programming languages
• Both JSON and XML can be fetched with an XMLHttpRequest
JSON is Unlike XML Because
• JSON doesn't use end tag
• JSON is shorter
• JSON is quicker to read and write
• JSON can use arrays
• The biggest difference is:
• XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript
function.
{"employees":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]}

<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>
JSON Data Types:
In JSON, values must be one of the following data types:
• a string
• a number
• an object (JSON object)
• an array
• a boolean
• null
Note: JSON values cannot be one of the following data types:
• a function, a date, undefined
JSON Strings
• Strings in JSON must be written in double quotes.
• Example: {"name":"John"}
JSON Numbers
• Numbers in JSON must be an integer or a floating point.
• Example: {"age":30}
JSON Objects
• Values in JSON can be objects.
• Example: {
"employee":{"name":"John", "age":30, "city":"New York"}
}
JSON Arrays
• Values in JSON can be arrays.
• Example: {
"employees":["John", "Anna", "Peter"]
}
JSON Booleans
• Values in JSON can be true/false.
• Example: {"sale":true}
JSON null
• Values in JSON can be null.
• Example: {"middlename":null}
JSON Object Literals:
• This is a JSON string:
'{"name":"John", "age":30, "car":null}'
• Inside the JSON string there is a JSON object literal:
{"name":"John", "age":30, "car":null}
• JSON object literals are surrounded by curly braces {}.
• JSON object literals contains key/value pairs.
• Keys and values are separated by a colon.
• Keys must be strings, and values must be a valid JSON data type:
• string
• number
• object
• array
• boolean
• null
• Each key/value pair is separated by a comma.
JavaScript Objects

• You can create a JavaScript object from a JSON object literal:


• Example
myObj = {"name":"John", "age":30, "car":null};
• Normally, you create a JavaScript object by parsing a JSON string:
• Example
myJSON = '{"name":"John", "age":30, "car":null}’;
myObj = JSON.parse(myJSON);
Accessing Object Values:
• You can access object values by using dot (.) notation:
• Example
const myJSON = '{"name":"John", "age":30, "car":null}’;
const myObj = JSON.parse(myJSON);
x = myObj.name;
• You can also access object values by using bracket ([]) notation:
• Example
const myJSON = '{"name":"John", "age":30, "car":null}’;
const myObj = JSON.parse(myJSON);
x = myObj["name"];
Looping an Object
• You can loop through object properties with a for-in loop:
• Example
const myJSON = '{"name":"John", "age":30, "car":null}’;
const myObj = JSON.parse(myJSON);
let text = "";
for (const x in myObj) {
text += x + ", "; }
• In a for-in loop, use the bracket notation to access the property values:
• Example
const myJSON = '{"name":"John", "age":30, "car":null}’;
const myObj = JSON.parse(myJSON);
let text = "";
for (const x in myObj) {
text += myObj[x] + ", "; }
JSON Array Literals:
• This is a JSON string:
'["Ford", "BMW", "Fiat"]'
• Inside the JSON string there is a JSON array literal:
["Ford", "BMW", "Fiat"]
• Arrays in JSON are almost the same as arrays in JavaScript.
• In JSON, array values must be of type string, number, object, array, boolean or
null.
• In JavaScript, array values can be all of the above, plus any other valid JavaScript
expression, including functions, dates, and undefined.
JavaScript Arrays

• You can create a JavaScript array from a literal:


• Example: myArray = ["Ford", "BMW", "Fiat"];
• You can create a JavaScript array by parsing a JSON string:
• Example
myJSON = '["Ford", "BMW", "Fiat"]’;
myArray = JSON.parse(myJSON);
Accessing Array Values
• You access array values by index:
• Example: myArray[0];
Arrays in Objects
• Objects can contain arrays:
• Example:{
"name":"John",
"age":30,
"cars":["Ford", "BMW", "Fiat"]
}
• You access array values by index:
• Example: myObj.cars[0];
Looping Through an Array:
• You can access array values by using a for-in loop:
• Example
for (let i in myObj.cars) {
x += myObj.cars[i];
}
• Or you can use a for loop:
• Example
for (let i = 0; i < myObj.cars.length; i++) {
x += myObj.cars[i];
}
JSON HTML:

Ref:
• https://www.geeksforgeeks.org/javascript-json-html/
• https://www.w3schools.com/js/js_json_html.asp

You might also like