Note PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

lOMoARcPSD|49748193

All five units IV

Neural Networks & Deep Learning (Jawaharlal Nehru Technological University,


Hyderabad)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

XML - XML stands for Extensible Mark-up Language, developed by W3C in 1996. It is a
text-based mark-up language derived from Standard Generalized Mark-up Language
(SGML). XML 1.0 was officially adopted as a W3C recommendation in 1998. XML was
designed to carry data, not to display data. XML is designed to be self-descriptive. XML is a
subset of SGML that can define your own tags. A Meta Language and tags describe the
content. XML Supports CSS, XSL, DOM. XML does not qualify to be a programming
language as it does not performs any computation or algorithms. It is usually stored in a
simple text file and is processed by special software that is capable of interpretingXML.
The Difference between XML and HTML
1. HTML is about displaying information, where asXML is about carrying information. In
other words, XML was created to structure, store, and transport information. HTML was
designed to display thedata.
2. Using XML, we can create own tags where as in HTML it is not possible instead it offers
several built intags.
3. XML is platform independent neutral and languageindependent.
4. XML tags and attribute names are case-sensitive where as in HTML it isnot.
5. XML attribute values must be single or double quoted where as in HTML it is not
compulsory.
6. XML elements must be properlynested.
7. All XML elements must have a closingtag.
Well Formed XML Documents
A "Well Formed" XML document must have the following correct XML syntax:
- XML documents must have a rootelement
- XML elements must have a closing tag(start tag must have matching endtag).
- XML tags are casesensitive
- XML elements must be properly nestedEx:<one><two>Hello</two></one>
- XML attribute values must bequoted
XML with correct syntax is "Well Formed" XML. XML validated against a DTD is "Valid"
XML.

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

What is Markup?
XML is a markup language that defines set of rules for encoding documents in a format that
is both human-readable andmachine-readable.
Example for XML Document
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!—xml declaration-->
<note>
<to>MRCET</to>
<from>MRGI</from>
<heading>KALPANA</heading>
<body>Hello, world! </body>
</note>
 Xml document begins with XML declaration statement: <? xml version="1.0"
encoding="ISO-8859-1"?>.
 The next line describes the root element of the document:<note>.
 This element is "the parent" of all otherelements.
 The next 4 lines describe 4child elements of the root: to, from, heading, and body. And
finally the last line defines the end of the root element : </note>.
 The XML declaration has no closing tag i.e.</?xml>
 The default standalone value is set to no. Setting it to yes tells the processor there are no
external declarations (DTD) required for parsing the document. The file name extension
used for xml program is.xml.
Valid XML document
If an XML document is well-formed and has an associated Document Type Declaration
(DTD), then it is said to be a valid XML document. We will study more about DTD in the
chapter XML - DTDs.
XML DTD
Document Type Definition purpose is to define the structure of an XML document. It defines
the structure with a list of defined elements in the xml document. Using DTD we can specify
the various elements types, attributes and their relationship with one another. Basically DTD
is used to specify the set of rules for structuring data in any XML file.
Why use a DTD?
XML provides an application independent way of sharing data. With a DTD, independent
groups of people can agree to use a common DTD for interchanging data. Your application
can use a standard DTD to verify that data that you receive from the outside world is valid.
You can also use a DTD to verify your own data.
DTD - XML building blocks
Various building blocks of XML are-
1. Elements: The basic entity is element. The elements are used for defining the tags. The
elements typically consist of opening and closing tag. Mostly only one element is used to
define a singletag.
Syntax1: <!ELEMENT element-name (element-content)>
Syntax 2: <!ELEMENT element-name (#CDATA)>
#CDATA means the element contains character data that is not supposed to be parsed by a
parser. or
Syntax 3: <!ELEMENT element-name (#PCDATA)>
#PCDATA means that the element contains data that IS going to be parsed by a parser. or

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

Syntax 4: <!ELEMENT element-name (ANY)>


The keyword ANY declares an element with any content.
Example:
<!ELEMENT note (#PCDATA)>
Elements with children (sequences)
Elements with one or more children are defined with the name of the children elements inside
the parentheses:
<!ELEMENT parent-name (child-element-name)>EX:<!ELEMENT student (id)>
<!ELEMENT id (#PCDATA)> or
<!ELEMENT element-name(child-element-name,child-element-name,. ..... )>
Example: <!ELEMENT note (to,from,heading,body)>
When children are declared in a sequence separated by commas, the children must appear in
the same sequence in the document. In a full declaration, the children must also be declared,
and the children can also have children. The full declaration of the note document will be:
<!ELEMENT note (to,from,heading,body)>
<!ELEMENTto (#CDATA)>
<!ELEMENTfrom (#CDATA)>
<!ELEMENT heading (#CDATA)>
<!ELEMENTbody (#CDATA)>

2. Tags
Tags are used to markup elements. A starting tag like <element_name> mark up the
beginning of an element, and an ending tag like </element_name> mark up the end of an
element.
Examples:
A body element: <body>body text in between</body>.
A message element: <message>some message in between</message>
3. Attribute: The attributes are generally used to specify the values of the element. These are
specified within the double quotes. Ex: <flagtype=‖true‖>
4. Entities
Entities as variables used to define common text. Entity references are references to entities.
Most of you will known the HTML entity reference: "&nbsp;" that is used to insert an extra
space in an HTML document. Entities are expanded when a document is parsed by an XML
parser.
The following entities are predefined in XML:
&lt; (<), &gt;(>), &amp;(&), &quot;(") and &apos;(').
5. CDATA: It stands for character data. CDATA is text that will NOT be parsed by a
parser. Tags inside the text will NOT be treated as markup and entities will not beexpanded.
6. PCDATA: It stands for Parsed Character Data(i.e., text). Any parsed character data should
not contain the markup characters. The markup characters are < or > or &. If we want to use
these characters then make use of &lt; , &gt; or &amp;. 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. Tags inside the text will be treated as markup and entities will be
expanded.
<!DOCTYPE note

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
Where PCDATA refers parsed character data. In the above xml document the elements to,
from, heading, body carries some text, so that, these elements are declared to carry text in
DTD file.
This definition file is stored with .dtd extension.
DTD identifier is an identifier for the document type definition, which may be the path to a
file on the system or URL to a file on the internet. If the DTD is pointing to external path, it
is called ExternalSubset.
The square brackets [ ] enclose an optional list of entity declarations called Internal Subset.
Types of DTD:
1. InternalDTD
2. ExternalDTD
1. Internal DTD
A DTD is referred to as an internal DTD if elements are declared within the XML files. To
refer it as internal DTD, standalone attribute in XML declaration must be set to yes. This
means, the declaration works independent of external source.
Syntax:
The syntax of internal DTD is as shown:
<!DOCTYPE root-element [element-declarations]>
Where root-element is the name of root element and element-declarations is where you
declare the elements.
Example:
Following is a simple example of internal DTD:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>
<address>
<name>Kalpana</name>
<company>MRCET</company>
<phone>(040) 123-4567</phone>
</address>
Let us go through the above code:
Start Declaration- Begin the XML declaration with following statement <?xml version="1.0"
encoding="UTF-8" standalone="yes" ?>

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

DTD- Immediately after the XML header, the document type declaration follows, commonly
referred to as the DOCTYPE:
<!DOCTYPE address [
The DOCTYPE declaration has an exclamation mark (!) at the start of the element name. The
DOCTYPE informs the parser that a DTD is associated with this XML document.
DTD Body- The DOCTYPE declaration is followed by body of the DTD, where you declare
elements, attributes, entities, and notations:
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone_no (#PCDATA)>
Several elements are declared here that make up the vocabulary of the <name> document.
<!ELEMENT name (#PCDATA)> defines the element name to be of type "#PCDATA".
Here #PCDATA means parse-able text data. End Declaration - Finally, the declaration
section of the DTD is closed using a closing bracket and a closing angle bracket (]>). This
effectively ends the definition, and thereafter, the XML document followsimmediately.
Rules
 The document type declaration must appear at the start of the document (preceded only by
the XML header) — it is not permitted anywhere else within thedocument.
 Similar to the DOCTYPE declaration, the element declarations must start with an
exclamationmark.
 The Name in the document type declaration must match the element type of the root
element.
External DTD
In external DTD elements are declared outside the XML file. They are accessed by
specifying the system attributes which may be either the legal .dtd file or a valid URL. To
refer it as external DTD, standalone attribute in the XML declaration must be set as no. This
means, declaration includes information from the externalsource.
Syntax Following is the syntax for external DTD:
<!DOCTYPE root-element SYSTEM "file-name">
where file-name is the file with .dtd extension.
Example The following example shows external DTDusage:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE address SYSTEM "address.dtd">
<address>
<name>Kalpana</name>
<company>MRCET</company>
<phone>(040) 123-4567</phone>
</address>
The content of the DTD file address.dtd are as shown:
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
Types
You can refer to an external DTD by using either system identifiers or public identifiers.

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

SYSTEM IDENTIFIERS
A system identifier enables you to specify the location of an external file containing DTD
declarations. Syntax is as follows:
<!DOCTYPE name SYSTEM "address.dtd" [...]>
As you can see, it contains keyword SYSTEM and a URI reference pointing to the location of
the document.
PUBLIC IDENTIFIERS
Public identifiers provide a mechanism to locate DTD resources and are written as below:
<!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN">
As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public
identifiers are used to identify an entry in a catalog. Public identifiers can follow any format;
however, a commonly used format is called Formal Public Identifiers, or FPIs.

XML Schemas
 XML Schema is commonly known as XML Schema Definition (XSD). It is used to
describe and validate the structure and the content of XML data. XML schema defines the
elements, attributes and data types. Schema element supports Namespaces. It is similar to
a database schema that describes the data in a database. XSD extension is“.xsd”.
 This can be used as an alternative to XML DTD. The XML schema became the W#C
recommendation in2001.
 XML schema defines elements, attributes, element having child elements, order of child
elements. It also defines fixed and default values of elements andattributes.
 XML schema also allows the developer to us datatypes.

Syntax :You need to declare a schema in your XML document as follows:


<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
Example : contact.xsd
The following example shows how to use schema:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="contact">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
<xs:element name="phone" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The basic idea behind XML Schemas is that they describe the legitimate format that an XML
document can take.
XML Document: myschema.xml
<?xml version="1.0" encoding="UTF-8"?>

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

<contact xmlns:xsi=http://www.w3.org/2001/XMLSchema-
instancexsi:noNamespaceSchemaLocation=”contact.xsd”>
<name>KALPANA</name>
<company>04024056789</company>
<phone>9876543210</phone>
</contact>
Limitations of DTD:
 There is no built-in data type inDTDs.
 No new data type can be created inDTDs.
 The use of cardinality (no. of occurrences) in DTDs islimited.
 Namespaces are notsupported.
 DTDs provide very limited support for modularity andreuse.
 We cannot put any restrictions on textcontent.
 Defaults for elements cannot bespecified.
 DTDs are written in a non-XML format and are difficult tovalidate.
Strengths of Schema:
 XML schemas provide much greater specificity thanDTDs.
 They supports large number of built-in-datatypes.
 They arenamespace-aware.
 They are extensible to futureadditions.
 They support theuniqueness.
 It is easier to define data facets (restrictions ondata).

SCHEMA STRUCTURE
The Schema Element
<xs: schema xmlns: xs="http://www.w3.org/2001/XMLSchema">
Element definitions
As we saw in the chapter XML - Elements, elements are the building blocks of XML
document. An element can be defined within an XSD as follows:
<xs:element name="x" type="y"/>
Data types:
These can be used to specify the type of data stored in an Element.
 String (xs:string)
 Date (xs:date or xs:time)
 Numeric (xs:integeror xs:decimal)
 Boolean (xs:boolean)
EX: Sample.xsd
<?xml version=‖1.0‖ encoading=‖UTF-8‖?>
<xs:schema xmlns:xs=http://www.w3.org/XMLSchema>
<xs:element name="sname‖ type=‖xs:string"/>
/* <xs:element name="dob” type=”xs:date"/>
<xs:element name="dobtime” type=”xs:time"/>
<xs:element name="marks” type=”xs:integer"/>
<xs:element name="avg” type=”xs:decimal"/>
<xs:element name="flag” type=”xs:boolean"/>*/

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

</xs:schema>
Sample.xml:
<?xml version=‖1.0‖ encoading=‖UTF-8‖?>
<sname xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="sample.xsd">
Kalpana /*yyyy-mm-dd 23:14:34 600 92.5 true/false */
</sname>
Definition Types
You can define XML schema elements in following ways:
Simple Type - Simple type element is used only in the context of the text. Some of
predefined simple types are: xs:integer, xs:boolean, xs:string, xs:date. Forexample:
<xs:element name="phone_number" type="xs:int" />
<phone>9876543210</phone>
Default and Fixed Values for Simple Elements
In the following example the default value is "red":
<xs:element name="color" type="xs:string" default="red"/>
In the following example the fixed value is "red":
<xs:element name="color" type="xs:string" fixed="red"/>

Complex Type - A complex type is a container for other element definitions. This allows you
to specify which child elements an element can contain and to provide some structure within
your XML documents. For example:
<xs:element name="Address">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="company" type="xs:string"/>
<xs:element name="phone" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
In the above example, Address element consists of child elements. This is a container for
other <xs:element> definitions, that allows to build a simple hierarchy of elements in the
XML document.
Global Types - With global type, you can define a single type in your document, which can
be used by all other references. For example, suppose you want to generalize the person and
company for different addresses of the company. In such case, you can define a general type
as below:
<xs:element name="AddressType">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="company" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Now let us use this type in our example as below:

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

<xs:element name="Address1">
<xs:complexType>
<xs:sequence>
<xs:element name="address" type="AddressType" />
<xs:element name="phone1" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Address2">
<xs:complexType>
<xs:sequence>
<xs:element name="address" type="AddressType" />
<xs:element name="phone2" type="xs:int" />
</xs:sequence></xs:complexType></xs:element>
Instead of having to define the name and the company twice (once for Address1 and once for
Address2), we now have a single definition. This makes maintenance simpler, i.e., if you
decide to add "Postcode" elements to the address, you need to add them at just one place.
Attributes
Simple elements cannot have attributes. If an element has attributes, it is considered to be of a
complex type. But the attribute itself is always declared as a simple type. Attributes in XSD
provide extra information within an element. Attributes have name and type property as
shown below:
<xs:attribute name="x" type="y"/>
Ex: <lastname lang="EN">Smith</lastname>
<xs:attribute name="lang" type="xs:string"/>
Default and Fixed Values for Attributes
<xs:attribute name="lang" type="xs:string" default="EN"/>
<xs:attribute name="lang" type="xs:string" fixed="EN"/>
Optional and Required Attributes
Attributes are optional by default. To specify that the attribute is required, use the "use"
attribute:
<xs:attribute name="lang" type="xs:string" use="required"/>
Restrictions on Content
When an XML element or attribute has a data type defined, it puts restrictions on the
element's or attribute's content. If an XML element is of type "xs:date" and contains a string
like "Hello World", the element will not validate.
Restrictions on Values:
The value of age cannot be lower than 0 or greater than 120:
<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>

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

Restrictions on a Set of Values


The example below defines an element called "car" with a restriction. The only acceptable
values are: Audi, Golf, BMW:
<xs:element name="car">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Audi"/>
<xs:enumeration value="Golf"/>
<xs:enumeration value="BMW"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
Restrictions on Length
To limit the length of a value in an element, we would use the length, maxLength, and
minLength constraints. The value must be exactly eight characters:
<xs:element name="password">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:lengthvalue="8"/> [<xs:minLengthvalue="5"/> <xs:maxLengthvalue="8"/>]
</xs:restriction></xs:simpleType></xs:element>

XSD Indicators
We can control HOW elements are to be used in documents with indicators.
Indicators: There are seven indicators
Order indicators:
 All
 Choice
 Sequence
Occurrence indicators:
 maxOccurs
 minOccurs
Group indicators:
 Groupname
 attributeGroupname

Order Indicators
Order indicators are used to define the order of the elements.
All Indicator
The <all> indicator specifies that the child elements can appear in any order, and that each
child element must occur only once:
<xs:element name="person">
<xs:complexType>
<xs:all>
<xs:element name="firstname"type="xs:string"/>
<xs:element name="lastname"type="xs:string"/>
</xs:all>
</xs:complexType>
</xs:element>

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

Note: When using the <all> indicator you can set the <minOccurs> indicator to 0 or 1 and the
<maxOccurs> indicator can only be set to 1 (the <minOccurs> and <maxOccurs> are
described later).
Choice Indicator
The <choice> indicator specifies that either one child element or another can occur:
<xs:element name="person">
<xs:complexType>
<xs:choice>
<xs:element name="employee" type="employee"/>
<xs:element name="member" type="member"/>
</xs:choice></xs:complexType> </xs:element>
Sequence Indicator
The <sequence> indicator specifies that the child elements must appear in a specific order:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence></xs:complexType></xs:element>
Occurrence Indicators
Occurrence indicators are used to define how often an element can occur.
Note: For all "Order" and "Group" indicators (any, all, choice, sequence, group name, and group
reference) the default value for maxOccurs and minOccurs is 1.
maxOccurs Indicator
The <maxOccurs> indicator specifies the maximum number of times an element can occur:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string" maxOccurs="10"/>
</xs:sequence>
</xs:complexType>
</xs:element>

minOccurs Indicator
The <minOccurs> indicator specifies the minimum number of times an element can occur:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string" maxOccurs="10" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Tip: To allow an element to appear an unlimited number of times, use the
maxOccurs="unbounded" statement:

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

EX: An XML file called "Myfamily.xml":


<?xml version="1.0" encoding="UTF-8"?>
<persons xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="family.xsd">
<person>
<full_name>KALPANA</full_name>
<child_name>mrcet</child_name>
</person>
<person>
<full_name>Tove Refsnes</full_name>
<child_name>Hege</child_name>
<child_name>Stale</child_name>
<child_name>Jim</child_name>
<child_name>Borge</child_name>
</person>
<person>
<full_name>Stale Refsnes</full_name>
</person>
</persons>
The XML file above contains a root element named "persons". Inside this root element we
have defined three "person" elements. Each "person" element must contain a "full_name"
element and it can contain up to five "child_name" elements.
Here is the schema file "family.xsd":
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
xmlns:xs=http://www.w3.org/2001/XMLSchemaelementFor
mDefault="qualified">
<xs:element name="persons">
<xs:complexType>
<xs:sequence>
<xs:element name="person" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string" minOccurs="0" maxOccurs="5"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Group Indicators: Group indicators are used to define related sets of elements.
Element Groups
Element groups are defined with the group declaration, like this:
<xs:group name="groupname">
...
</xs:group>

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

You must define an all, choice, or sequence element inside the group declaration. The
following example defines a group named "persongroup", that defines a group of elements
that must occur in an exact sequence:
<xs:group name="persongroup">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:element name="birthday" type="xs:date"/>
</xs:sequence>
</xs:group>
After you have defined a group, you can reference it in another definition, like this:
<xs:element name="person" type="personinfo"/>
<xs:complexType name="personinfo">
<xs:sequence>
<xs:group ref="persongroup"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:complexType>

Attribute Groups
Attribute groups are defined with the attributeGroup declaration, like this:
<xs:attributeGroup name="groupname">
...
</xs:attributeGroup>
The following example defines an attribute group named "personattrgroup":
<xs:attributeGroup name="personattrgroup">
<xs:attribute name="firstname" type="xs:string"/>
<xs:attribute name="lastname" type="xs:string"/>
<xs:attribute name="birthday" type="xs:date"/>
</xs:attributeGroup>
After you have defined an attribute group, you can reference it in another definition, like this:
<xs:element name="person">
<xs:complexType>
<xs:attributeGroup ref="personattrgroup"/></xs:complexType></xs:element>

Example Program: "shiporder.xml"


<?xml version="1.0" encoding="UTF-8"?>
<shiporder orderid="889923"
xmlns:xsi=http://www.w3.org/2001/XMLSchema-
instancexsi:noNamespaceSchemaLocation="shiporder.xs
d">
<orderperson>John Smith</orderperson>
<shipto>
<name>Ola Nordmann</name>
<address>Langgt 23</address>

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

<city>4000 Stavanger</city>

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

<country>Norway</country>
</shipto>
<item>
<title>Empire Burlesque</title>
<note>Special Edition</note>
<quantity>1</quantity>
<price>10.90</price>
</item>
<item>
<title>Hide yourheart</title> <quantity>1</quantity>
<price>9.90</price></item>
</shiporder>
Create an XML Schema "shiporder.xsd":
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="shiporder">
<xs:complexType>
<xs:sequence>
<xs:element name="orderperson" type="xs:string"/>
<xs:element name="shipto">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="item" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="note" type="xs:string" minOccurs="0"/>
<xs:element name="quantity" type="xs:positiveInteger"/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="orderid" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>

XML DTD vs XML Schema


The schema has more advantages over DTD. A DTD can have two types of data in it, namely
the CDATA and the PCDATA. The CDATA is not parsed by the parser whereas the
PCDATA is parsed. In a schema you can have primitive data types and custom data types
like you have used inprogramming.

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

Schema vs. DTD


• XML Schemas are extensible to future additions
• XML Schemas are richer and more powerful than DTDs
• XML Schemas are written in XML
• XML Schemas support datatypes
• XML Schemas support namespaces
XML Parsers
An XML parser converts an XML document into an XML DOM object - which can then be
manipulated with a JavaScript.

Two types of XML parsers:


 ValidatingParser
• It requires document type declaration
• It generates error if document doesnot
o Conform with DTDand
o Meet XML validityconstraints
 Non-validating Parser
• It checks well-formedness for xmldocument
• It can ignore externalDTD

What is XML Parser?


XML Parser provides way how to access or modify data present in an XML document. Java
provides multiple options to parse XML document. Following are various types of parsers
which are commonly used to parse XML documents.
Types of parsers:
 Dom Parser - Parses the document by loading the complete contents of the document and
creating its complete hiearchical tree inmemory.
 SAX Parser - Parses the document on event based triggers. Does not load the complete
document into thememory.
 JDOM Parser - Parses the document in similar fashion to DOM parser but in more easier
way.
 StAX Parser - Parses the document in similar fashion to SAX parser but in more efficient
way.
 XPath Parser - Parses the XML based on expression and is used extensively in
conjuction withXSLT.
 DOM4J Parser - A java library to parse XML, XPath and XSLT using Java Collections
Framework , provides support for DOM, SAX andJAXP.

DOM-Document Object Model


The Document Object Model protocol converts an XML document into a collection of
objects in your program. XML documents have a hierarchy of informational units called
nodes; this hierarchy allows a developer to navigate through the tree looking for specific
information. Because it is based on a hierarchy of information, the DOM is said to be tree
based. DOM is a way of describing those nodes and the relationships betweenthem.

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

You can then manipulate the object model in any way that makes sense. This mechanism is
also known as the "random access" protocol, because you can visit any part of the data at any
time. You can then modify the data, remove it, or insert new data.

The XML DOM, on the other hand, also provides an API that allows a developer to add, edit,
move, or remove nodes in the tree at any point in order to create an application. A DOM
parser creates a tree structure in memory from the input document and then waits for requests
from client. A DOM parser always serves the client application with the entire document no
matter how much is actually needed by the client. With DOM parser, method calls in client
application have to be explicit and forms a kind of chained method calls.
Document Object Model is for defining the standard for accessing and manipulating XML
documents. XML DOM is used for
 Loading the xmldocument
 Accessing the xmldocument
 Deleting the elements of xmldocument
 Changing the elements of xml document
According to the DOM, everything in an XML document is a node. It considers
 The entire document is a documentnode
 Every XML element is an elementnode
 The text in the XML elements are textnodes
 Every attribute is an attributenode
 Comments are comment nodes

The W3C DOM specification is divided into three major parts:


DOM Core- This portion defines the basic set of interfaces and objects for any structured
documents.
XML DOM- This part specifies the standard set of objects and interfaces for XML
documents only.
HTML DOM- This part specifies the objects and interfaces for HTML documents only.
DOM Levels
 Level 1 Core: W3C Recommendation, October1998
 It has feature for primitive navigation and manipulation of XMLtrees
 other Level 1 features are: All HTMLfeatures
 Level 2 Core: W3C Recommendation, November2000
 It adds Namespace support and minor newfeatures
 other Level 2 features are: Events, Views, Style, Traversal andRange
 Level 3 Core: W3C Working Draft, April2002
 It supports: Schemas, XPath, XSL, XSLT
We can access and parse the XML document in two ways:
 Parsingusing DOM (treebased)
 Parsing using SAX (Eventbased)
Parsing the XML doc. using DOM methods and properties are called as tree based approach
whereas using SAX (Simple Api for Xml) methods and properties are called as event based
approach.

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

Steps to Using DOM Parser


Let‘s note down some broad steps involved in using a DOM parser for parsing any XML file
injava.

DOM based XML Parsing:(tree based)


JAXP is a tool, stands for Java Api for Xml Processing, used for accessing and manipulating
xml document in a tree based manner.
The following DOM javaClasses are necessary to process the XML document:
 DocumentBuilderFactory class creates the instance ofDocumentBuilder.
 DocumentBuilder produces a Document (a DOM) that conforms to the DOM specification.
The following methods and properties are necessary to process the XMLdocument:
Property Meaning
nodeName Finding the name of the node
nodeValue Obtaining value of the node
parentNode To get parnet node
childNodes Obtain child nodes
Attributes For getting the attributes values
Method Meaning
getElementByTagName(name) To access the element by specifying its name
appendChild(node) To insert a child node
removeChild(node) To remove existing child node

#document <html>
<body> BODY
HTML <h1>Heading 1</h1>
lastChild
parentNode

<p>Paragraph.</p>
firstChild

HEAD
<h2>Heading 2</h2>
<p>Paragraph.</p>
BODY </body> nextSibling nextSibling nextSibling
</html>
H1
#text
H1 P H2 P
previousSibling previousSibling previousSibling
parentNode

parentNode

parentNode

parentNode

P
firstChild

firstChild

firstChild

firstChild
lastChild

lastChild

lastChild

lastChild

#text

H2
#text

P #text #text #text #text


#text

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

DOM Document Object


 There are12 types of nodes in a DOM Documentobject
1. Document node 7. EntityReferencenode
2. Elementnode 8. Entitynode
3. Textnode 9. Commentnode
4. Attributenode 10. DocumentTypenode
5. Processing instructionnode 11. DocumentFragmentnode
6. CDATA Sectionnode 12. Notationnode

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

Examples for Document method


<html>
<head>
<title>Change the Background</title>
</head>
<body>
<script language = "JavaScript">
function background()
{ var color = document.bg.color.value;
document.body.style.backgroundColor=color; }
</script>
<form name="bg">
Type the Color Name:<input type="text" name="color" size="20">
<br>
Click the Submit Button to change this Background color as your Color.
<br>
<input type="button" value="Submit" onClick='background()'>
</form>
</body>
</html>
DOM Advantages & Disadvantages
ADVANTAGES
- Robust API for the DOMtree
- Relativelysimpletomodifythedatastructureandextractdata
- It is goodwhen randomaccesstowidelyseparated partsofadocumentisrequired
- It supports both read and writeoperations
-
Disadvantages
- Stores the entire document in memory.
- It is memory inefficient .

Web Technologies Page 51

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

ANGUALR JS :

AngularJS is an open-source web application framework. It was originally


developed in 2009 by Misko Hevery and Adam Abrons. It is now maintained
by Google. Its latest version is 1.2.21.
Definition of AngularJS as put by its official documentation is as follows:
AngularJS is a structural framework for dynamic web applications. It
lets you use HTML as your template language and lets you extend
HTML's syntax to express your application components clearly and
succinctly. Its data binding and dependency injection eliminate much
of the code you currently have to write. And it all happens within the
browser, making it an ideal partner with any server technology.

GeneralFeatures

The general features of AngularJS are as follows:

 AngularJS is a efficient framework that can create Rich Internet Applications (RIA).

 AngularJS provides developers an options to write client side applications using JavaScript in a
clean Model View Controller (MVC) way.

 Applications written in AngularJS are cross-browser compliant. AngularJS automatically


handles JavaScript code suitable for each browser.

 AngularJS is open source, completely free, and used by thousands of developers around the
world. It is licensed under the Apache license version 2.0.

Overall, AngularJS is a framework to build large scale, high-performance,


and easy- to-maintain web applications.

CoreFeatures

The core features of AngularJS are as follows:


 Data-binding: It is the automatic synchronization of data between model andview components.

 Scope: These are objects that refer to the model. They act as a glue betweencontroller and view.

1
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

Angular
JS
 Controller: These are JavaScript functions bound to a particular scope.
 Services: AngularJS comes with several built-in services such as $http to make a
XMLHttpRequests. These are singleton objects which are instantiatedonly once in app.

 Filters: These select a subset of items from an array and returns a new array.

 Directives: Directives are markers on DOM elements such as elements, attributes, css, and more.
These can be used to create custom HTML tags thatserve as new, custom widgets. AngularJS has
built-in directives such as ngBind, ngModel, etc.

 Templates: These are the rendered view with information from the controller and model. These
can be a single file (such as index.html) or multiple views in one page using partials.

 Routing: It is concept of switching views.

 Model View Whatever: MVW is a design pattern for dividing an application into different parts
called Model, View, and Controller, each with distinct responsibilities. AngularJS does not
implement MVC in the traditional sense, but rather something closer to MVVM (Model-View-
ViewModel). The Angular JS team refers it humorously as Model View Whatever.

 Deep Linking: Deep linking allows to encode the state of application in the URL so that it can
be bookmarked. The application can then be restored fromthe URL to the same state.

 Dependency Injection: AngularJS has a built-in dependency injection subsystem that helps the
developer to create, understand, and test the applications easily.

Concepts

The following diagram depicts some important parts of AngularJS which


we will discuss in detail in the subsequent chapters.

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

Angular
JS

AdvantagesofAngularJS

The advantages of AngularJS are:


 It provides the capability to create Single Page Application in a very clean andmaintainable way.

 It provides data binding capability to HTML. Thus, it gives user a rich andresponsive
experience.

 AngularJS code is unit testable.

 AngularJS uses dependency injection and make use of separation of concerns.

 AngularJS provides reusable components.

 With AngularJS, the developers can achieve more functionality with shortcode.

 In AngularJS, views are pure html pages, and controllers written in JavaScriptdo the business
processing.

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

Angular
JS
On the top of everything, AngularJS applications can run on all major
browsers and smart phones, including Android and iOS based
phones/tablets.

DisadvantagesofAngularJS

Though AngularJS comes with a lot of merits, here are some points of concern:
 Not secure : Being JavaScript only framework, application written in AngularJS are not safe.
Server side authentication and authorization is must to keep an application secure.

 Not degradable: If the user of your application disables JavaScript, then nothing would be
visible, except the basic page.

AngularJSDirectives

The AngularJS framework can be divided into three major parts:


 ng-app : This directive defines and links an AngularJS application to HTML.

 ng-model : This directive binds the values of AngularJS application data to HTML input
controls.

 ng-bind : This directive binds the AngularJS application data to HTML tag

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

Example
Now let us write a simple example using AngularJS library. Let us create
an HTML file myfirstexample.html shown as below:

<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-
beta.17/angular.min.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="HelloController" >
<h2>Welcome {{helloTo.title}} to the world of Tutorialspoint!</h2>
</div>
<script>
angular.module("myapp", [])
.controller("HelloController", function($scope) {
$scope.helloTo = {};
$scope.helloTo.title = "AngularJS";
});
</script>
</body>
</html>

5
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

Let us go through the above code in detail:

Include AngularJS
We include the AngularJS JavaScript file in the HTML page so that we can use it:

<head>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</head>

You can check the latest version of AngularJS on its official website.

Point to AngularJS app


Next, it is required to tell which part of HTML contains the AngularJS app.
You can do this by adding the ng-app attribute to the root HTML element of
the AngularJS app. You can either add it to the html element or the body
element as shown below:

<body ng-app="myapp">
</body>

View
The view is this part:

<div ng-controller="HelloController" >


<h2>Welcome {{helloTo.title}} to the world of Tutorialspoint!</h2>
</div>

ng-controller tells AngularJS which controller to use with this view.


helloTo.title tells AngularJS to write the model value named helloTo.title in
HTML at this location.

Controller
The controller part is:

<script>
angular.module("myapp", [])
.controller("HelloController", function($scope) {
$scope.helloTo = {};
$scope.helloTo.title = "AngularJS";
});

6
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

</script>

This code registers a controller function named HelloController in the angular


module named myapp. We will study more about modules and controllers in their
Angular
respective chapters. The controller function is registered in angular via the
angular.module(...).controller(...) function call.
The $scope parameter model is passed to the controller function. The
controller function adds a helloTo JavaScript object, and in that object it
adds a title field.

Model View Controller or MVC as it is popularly called, is a software design


pattern for developing web applications. A Model View Controller pattern is
made up of the following three parts:
 Model - It is the lowest level of the pattern responsible for maintaining data.

 View - It is responsible for displaying all or a portion of the data to the user.

 Controller - It is a software Code that controls the interactions between theModel and View.

MVC is popular because it isolates the application logic from the user
interface layer and supports separation of concerns. The controller receives

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

all requests for the application and then works with the model to prepare
any data needed by the view. The view then uses the data prepared by the
controller to generate a final presentable response. The MVC abstraction can
be graphically represented as follows.
Before creating actual Hello World ! application using AngularJS, let us see
the parts of a AngularJS application. An AngularJS application consists of
following three important parts:
 ng-app : This directive defines and links an AngularJS application to HTML.

 ng-model : This directive binds the values of AngularJS application data toHTML input
controls.

 ng-bind : This directive binds the AngularJS Application data to HTML tags.

CreatingAngularJSApplication

Step 1: Load framework


Being a pure JavaScript framework, it can be added using <Script> tag.

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
</script>

Step 2: Define AngularJS application using ng-app directive.

<div ng-app="">
...
</div>

Step 3: Define a model name using ng-model directive.

<p>Enter your Name: <input type="text" ng-model="name"></p>

Step 4: Bind the value of above model defined using ng-bind directive.

<p>Hello <span ng-bind="name"></span>!</p>

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

testAngularJS.htm

<html>
<title>AngularJS First Application</title>
<body>
<h1>Sample Application</h1>
<div ng-app="">
<p>Enter your Name: <input type="text" ng-model="name"></p>
<p>Hello <span ng-bind="name"></span>!</p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
</script>
</body>
</html>

Output
Open the file testAngularJS.htm in a web browser. Enter your name and see theresult.

Downloaded by Shiva Gopi Boddu ([email protected])


lOMoARcPSD|49748193

HowAngularJSIntegrateswithHTML

 The ng-app directive indicates the start of AngularJS application.


Angular
 The ng-model directive creates a model variable named name, which can beused with the
HTML page and within the div having ng-app directive.

 The ng-bind then uses the name model to be displayed in the HTML <span>tag whenever user
enters input in the text box.

 Closing </div> tag indicates the end of AngularJS application.


AngularJS directives are used to extend HTML. They are special attributes
starting with ng-prefix. Let us discuss the following directives:
 ng-app - This directive starts an AngularJS Application.

 ng-init - This directive initializes application data.

 ng-model - This directive defines the model that is variable to be used inAngularJS.

 ng-repeat - This directive repeats HTML elements for each item in acollection.

ng-appdirective

The ng-app directive starts an AngularJS Application. It defines the root


element. It automatically initializes or bootstraps the application when the
web page containing AngularJS Application is loaded. It is also used to load
various AngularJS modules in AngularJS Application. In the following
example, we define a default AngularJS application using ng-app attribute of
a <div> element.

<div ng-app="">
...
</div>

ng-initdirective

The ng-init directive initializes an AngularJS Application data. It is used to


assign values to the variables. In the following example, we initialize an
array of countries. We use JSON syntax to define the array of countries.

<div ng-app="" ng-init="countries=[{locale:'en-US',name:'United States'},


{locale:'en-GB',name:'United Kingdom'},
{locale:'en-FR',name:'France'}]">

...
</div>

10
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

ng-modeldirective

The ng-model directive defines the model/variable to be used in AngularJS


Application. In the following example, we define a model named name.

<div ng-app="">
...
<p>Enter your Name: <input type="text" ng-model="name"></p>
</div>

ng-repeatdirective

The ng-repeat directive repeats HTML elements for each item in a collection.
In the following example, we iterate over the array of countries.

<div ng-app="">
...
<p>List of Countries with locale:</p>
<ol>
<li ng-repeat="country in countries">
{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
</li>
</ol>
</div>

Example
The following example shows the use of all the above-mentioned directives.

testAngularJS.htm

<html>
<title>AngularJS Directives</title>
<body>
<h1>Sample Application</h1>
<div ng-app="" ng-init="countries=[{locale:'en-US',name:'United States'},
{locale:'en-GB',name:'United Kingdom'},
{locale:'en-FR',name:'France'}]">
<p>Enter your Name: <input type="text" ng-model="name"></p>

11
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

Expressions are used to bind application data to HTML. Expressions are


written inside double curly braces such as in {{ expression}}. Expressions
behave similar to ng- bind directives. AngularJS expressions are pure
JavaScript expressions and output the data where they are used.

Using numbers

<p>Expense on Books : {{cost * quantity}} Rs</p>

Using String

<p>Hello {{student.firstname + " " + student.lastname}}!</p>

<p>Roll No: {{student.rollno}}</p>


Using Object

Using Array

<p>Marks(Math): {{marks[3]}}</p>
Example
The following example shows the use of all the above-mentioned expressions:

testAngularJS.htm

<html>
<title>AngularJS Expressions</title>
<body>
<h1>Sample Application</h1>
<div ng-app="" ng-init="quantity=1;cost=30;
student={firstname:'Mahesh',lastname:'Parashar',rollno:101};marks=[80,90,75,73,60]">
<p>Hello {{student.firstname + " " + student.lastname}}!</p>
<p>Expense on Books : {{cost * quantity}} Rs</p>
<p>Roll No: {{student.rollno}}</p>
<p>Marks(Math): {{marks[3]}}</p>

Output
Open the file testAngularJS.htm in a web browser and see the result.

12
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

13
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

Angular

AngularJS application mainly relies on controllers to control the flow of data


in the application. A controller is defined using ng-controller directive. A
controller is a JavaScript object that contains attributes/properties, and
functions. Each controller accepts $scope as a parameter, which refers to
the application/module that the controller needs to handle.

<div ng-app="" ng-controller="studentController">


...
</div>
Here, we declare a controller named studentController, using the ng-
controller directive. We define it as follows:

<script>
function studentController($scope) {
$scope.student = { firstName:
"Mahesh", lastName:
"Parashar",fullName:
function() {
var studentObject; studentObject =
$scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
}
</script>
 The studentController is defined as a JavaScript object with $scope as anargument.

 The $scope refers to application which uses the studentController object.

 The $scope.student is a property of studentController object.

 The firstName and the lastName are two properties of $scope.student object.We pass the default
values to them.

 The property fullName is the function of $scope.student object, which returnsthe combined name.

14
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

Angular
JS
 In the fullName function, we get the student object and then return thecombined name.

 As a note, we can also define the controller object in a separate JS file andrefer that file in the
HTML page.

Now we can use studentController's student property using ng-model or using


expressions as follows:

Enter first name: <input type="text" ng-model="student.firstName"><br>Enter last name:


<input type="text" ng-model="student.lastName"><br>
<br>
You are entering: {{student.fullName()}}
 We bound student.firstName and student.lastname to two input boxes.
 We bound student.fullName() to HTML.
 Now whenever you type anything in first name and last name input boxes,you can see the full
name getting updated automatically.

Example
The following example shows the use of controller:

testAngularJS.htm

<html>
<head>
<title>Angular JS Controller</title>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="" ng-controller="studentController">
Enter first name: <input type="text" ng-model="student.firstName"><br><br>Enter last name:
<input type="text" ng-model="student.lastName"><br>
<br>
You are entering: {{student.fullName()}}
</div>
<script>
function studentController($scope) {
$scope.student = {
firstName: "Mahesh",

15
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

lastName: "Parashar",
fullName: function() {
var studentObject; studentObject =
$scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
}
</script>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
</script>
</body>
</html>

Output
Open the file testAngularJS.htm in a web browser and see the result.

16
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

10. HTML DOM Angular

The following directives are used to bind application data to the attributes
of HTML DOM elements:

Name Description

ng-disabled Disables a given control.

ng-show Shows a given control.

ng-hide Hides a given control.

ng-click Represents a AngularJS click event.

ng-disabledDirective

Add ng-disabled attribute to an HTML button and pass it a model. Bind the
model to a checkbox and see the variation.

<input type="checkbox" ng-model="enableDisableButton">Disable Button


<button ng-disabled="enableDisableButton">Click Me!</button>

ng-showDirective

Add ng-show attribute to an HTML button and pass it a model. Bind the
model to a checkbox and see the variation.

<input type="checkbox" ng-model="showHide1">Show Button


<button ng-show="showHide1">Click Me!</button>

ng-hideDirective

Add ng-hide attribute to an HTML button and pass it a model. Bind the
model to a checkbox and see the variation.

<input type="checkbox" ng-model="showHide2">Hide Button


<button ng-hide="showHide2">Click Me!</button>

17
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

Angular
JS
ng-clickDirective

Add ng-click attribute to an HTML button and update a model. Bind the
model to HTML and see the variation.

<p>Total click: {{ clickCounter }}</p></td>


<button ng-click="clickCounter = clickCounter + 1">Click Me!</button>

Example
The following example shows use of all the above mentioned directives.

testAngularJS.htm

<html>
<head>
<title>AngularJS HTML DOM</title>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="">
<table border="0">
<tr>
<td><input type="checkbox" ng-model="enableDisableButton">DisableButton</td>
<td><button ng-disabled="enableDisableButton">Click Me!</button></td>
</tr>
<tr>
<td><input type="checkbox" ng-model="showHide1">Show Button</td>
<td><button ng-show="showHide1">Click Me!</button></td>
</tr>
<tr>
<td><input type="checkbox" ng-model="showHide2">Hide Button</td>
<td><button ng-hide="showHide2">Click Me!</button></td>
</tr>
<tr>
<td><p>Total click: {{ clickCounter }}</p></td>
<td><button ng-click="clickCounter = clickCounter + 1">Click

18
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

Angular
JS

Me!</button></td>
</tr>
</table>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
</script>
</body>
</html>

Output
Open the file testAngularJS.htm in a web browser and see the result.

19
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

11. MODULES Angular

AngularJS supports modular approach. Modules are used to separate logic


such as services, controllers, application etc. from the code and maintain the
code clean. We define modules in separate js files and name them as per the
module.js file. In the following example, we are going to create two
modules:
 Application Module - used to initialize an application with controller(s).
 Controller Module - used to define the controller.

ApplicationModule

Here is a file named mainApp.js that contains the following code:

var mainApp = angular.module("mainApp", []);

Here, we declare an application mainApp module using angular.module


function and pass an empty array to it. This array generally contains
dependent modules.

ControllerModule

studentController.js
mainApp.controller("studentController", function($scope) {
$scope.student = { firstName:
"Mahesh", lastName:
"Parashar",fees:500,
subjects:[
{name:'Physics',marks:70},
{name:'Chemistry',marks:80},
{name:'Math',marks:65},
{name:'English',marks:75},
{name:'Hindi',marks:67}
],
fullName: function() {var
studentObject;

20
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

Angular
JS

studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
Here, we declare a controller studentController module using mainApp.controllerfunction.

UseModules

<div ng-app="mainApp" ng-controller="studentController">


..
<script src="mainApp.js"></script>
<script src="studentController.js"></script>
Here, we use application module using ng-app directive, and controller
using ng- controller directive. We import the mainApp.js and
studentController.js in the main HTML page.

Example
The following example shows use of all the above mentioned modules.

testAngularJS.htm

21
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

Angular
JS

}
</style>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="mainApp" ng-controller="studentController">
<table border="0">
<tr><td>Enter first name:</td><td><input type="text" ng-
model="student.firstName"></td></tr>
<tr><td>Enter last name: </td><td><input type="text" ng-
model="student.lastName"></td></tr>
<tr><td>Name: </td><td>{{student.fullName()}}</td></tr>
<tr><td>Subject:</td><td>
<table>
<tr>
<th>Name</th>
<th>Marks</th>
</tr>
<tr ng-repeat="subject in student.subjects">
<td>{{ subject.name }}</td>
<td>{{ subject.marks }}</td>
</tr>
</table>
</td></tr>
</table>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
</script>
<script src="mainApp.js"></script>
<script src="studentController.js"></script>
</body>
</html>

22
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

Angular
JS

mainApp.js

var mainApp = angular.module("mainApp", []);

studentController.js

mainApp.controller("studentController", function($scope) {
$scope.student = { firstName:
"Mahesh", lastName:
"Parashar",fees:500,
subjects:[
{name:'Physics',marks:70},
{name:'Chemistry',marks:80},
{name:'Math',marks:65},
{name:'English',marks:75},
{name:'Hindi',marks:67}
],
fullName: function() {var
studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});

Output
Open the file textAngularJS.htm in a web browser. See the result.

23
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

Angular
JS

24
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

Angular
12. FORMS

AngularJS enriches form filling and validation. We can use ng-click event to
handle the click button and use $dirty and $invalid flags to do the validation
in a seamless way. Use novalidate with a form declaration to disable any
browser-specific validation. The form controls make heavy use of AngularJS
events. Let us have a look at the events first.

Events

AngularJS provides multiple events associated with the HTML controls. For
example, ng-click directive is generally associated with a button. AngularJS
supports the following events:
 ng-click
 ng-dbl-click
 ng-mousedown
 ng-mouseup
 ng-mouseenter
 ng-mouseleave
 ng-mousemove
 ng-mouseover
 ng-keydown
 ng-keyup
 ng-keypress
 ng-change

ng-click

Reset data of a form using on-click directive of a button.

<input name="firstname" type="text" ng-model="firstName" required>


<input name="lastname" type="text" ng-model="lastName" required>
<input name="email" type="email" ng-model="email" required>
<button ng-click="reset()">Reset</button>
<script>
function studentController($scope) {

25
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

Angular
JS

$scope.reset = function(){
$scope.firstName = "Mahesh";
$scope.lastName = "Parashar";
$scope.email = "[email protected]";
}
$scope.reset();
}
</script>

ValidateData

The following can be used to track error.


 $dirty - states that value has been changed.
 $invalid- states that value entered is invalid.
 $error- states the exact error.

Example
The following example will showcase all the above-mentioned directives.

testAngularJS.htm

<html>
<head>
<title>Angular JS Forms</title>
<style>
table, th , td {
border: 1px solid grey; border-
collapse: collapse;padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}

26
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

Angular
JS

</style>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="" ng-controller="studentController">
<form name="studentForm" novalidate>
<table border="0">
<tr><td>Enter first name:</td><td><input name="firstname" type="text"ng-
model="firstName" required>
<span style="color:red" ng-show="studentForm.firstname.$dirty &&
studentForm.firstname.$invalid">
<span ng-show="studentForm.firstname.$error.required">First Name isrequired.</span>
</span>
</td></tr>
<tr><td>Enter last name: </td><td><input name="lastname" type="text" ng-model="lastName" required>
<span style="color:red" ng-show="studentForm.lastname.$dirty &&studentForm.lastname.$invalid">
<span ng-show="studentForm.lastname.$error.required">Last Name isrequired.</span>
</span>
</td></tr>
<tr><td>Email: </td><td><input name="email" type="email" ng-model="email"
length="100" required>
<span style="color:red" ng-show="studentForm.email.$dirty &&
studentForm.email.$invalid">
<span ng-show="studentForm.email.$error.required">Email isrequired.</span>
<span ng-show="studentForm.email.$error.email">Invalid emailaddress.</span>
</span>
</td></tr>
<tr><td><button ng-click="reset()">Reset</button></td><td><buttonng-
disabled=

27
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

Angular
JS

"studentForm.firstname.$dirty && studentForm.firstname.$invalid ||


studentForm.lastname.$dirty && studentForm.lastname.$invalid||
studentForm.email.$dirty && studentForm.email.$invalid"
ng-click="submit()">Submit</button></td></tr>
</table>
</form>
</div>
<script>
function studentController($scope) {
$scope.reset = function(){
$scope.firstName = "Mahesh";
$scope.lastName = "Parashar";
$scope.email = "[email protected]";
}
$scope.reset();
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
</script>
</body>
</html>

Output
Open the file testAngularJS.htm in a web browser and see the result.

28
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

Angular
JS

29
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193

Angular
JS

Downloaded by Shiva Gopi Boddu ([email protected])

You might also like