0% found this document useful (0 votes)
147 views

Introduction - To - XML Sem6 Bca

This document provides an introduction to XML, including: 1. XML was designed to transport and store data, while HTML was designed to display data. 2. XML allows authors to define their own tags and document structure, while HTML tags are predefined. 3. XML documents must follow syntax rules like having a root element, closing all tags, and properly nesting elements.

Uploaded by

aishwarya saji
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
147 views

Introduction - To - XML Sem6 Bca

This document provides an introduction to XML, including: 1. XML was designed to transport and store data, while HTML was designed to display data. 2. XML allows authors to define their own tags and document structure, while HTML tags are predefined. 3. XML documents must follow syntax rules like having a root element, closing all tags, and properly nesting elements.

Uploaded by

aishwarya saji
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

Introduction to XML

1. XML was designed to transport and store data.


2. HTML was designed to display data.
• What is XML?
1. XML stands for Extensible Markup Language
2. XML is a markup language much like HTML
3. XML was designed to carry data, not to display data
4. XML tags are not predefined. You must define your own tags
5. XML is designed to be self-descriptive
The Difference Between XML and HTML

1. XML is not a replacement for HTML.


2. XML and HTML were designed with different goals:
3. XML was designed to transport and store data, with focus on
what data is
4. HTML was designed to display data, with focus on how data
looks
5. HTML is about displaying information, while XML is about
carrying information.
Features of XML

• The following example is a note to manish, from amol, stored


as XML:
• <note>
<to>manish</to>
<from>amol</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
• The note above is quite self descriptive. It has sender and
receiver information, it also has a heading and a message
body.
• But still, this XML document does not DO anything. It is just
information wrapped in tags.
• The XML language has no predefined tags.
• The tags used in HTML are predefined. HTML documents can
only use tags defined in the HTML standard (like <p>, <h1>,
etc.).
• XML allows the author to define his/her own tags and his/her
own document structure.

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


carrying information.
• Well Formed XML Documents
• A "Well Formed" XML document has correct XML syntax.

• The syntax rules :


• XML documents must have a root element
• XML elements must have a closing tag
• XML tags are case sensitive
• XML elements must be properly nested
• XML attribute values must be quoted
• <?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>manish</to>
<from>amol</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
• The first line is the XML declaration. It defines the XML
version (1.0) and the encoding used (ISO-8859-1 =
Latin-1/West European character set).
• The next line describes the root element of the document
(like saying: "this document is a note"):
• <note>
• The next 4 lines describe 4 child elements of the root (to,
from, heading, and body):
• And finally the last line defines the end of the root element:
• XML Documents Form a Tree Structure
• 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).
Example:
• The image above represents one book in the XML below:
• <bookstore>
  <book category="COOKING">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category="CHILDREN">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="WEB">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>
XML Syntax Rules
• All XML Elements Must Have a Closing Tag
• In HTML, some elements do not have to have a closing tag:
• <p>This is a paragraph.
<br>
• In XML, it is illegal to omit the closing tag. All elements must
have a closing tag:
• <p>This is a paragraph.</p>
<br />
• XML Tags are Case Sensitive
• XML tags are case sensitive. The tag <Letter> is different from
the tag <letter>.
• Opening and closing tags must be written with the same case:
• <Message>This is incorrect</message>
<message>This is correct</message>
• XML Elements Must be Properly Nested
• In HTML, you might see improperly nested elements:
• <b><i>This text is bold and italic</b></i>
• In XML, all elements must be properly nested within each
other:
• <b><i>This text is bold and italic</i></b>
• XML Documents Must Have a Root Element
• XML documents must contain one element that is the parent
of all other elements. This element is called the root element.
• <root>
  <child>
    <subchild>.....</subchild>
  </child>
</root>
• Entity References
• Some characters have a special meaning in XML.
• If you place a character like "<" inside an XML element, it will
generate an error because the parser interprets it as the start
of a new element.
• This will generate an XML error:
• <message>if salary < 1000 then</message>
• To avoid this error, replace the "<" character with an
• entity reference:
• <message>if salary &lt; 1000 then</message>
• There are 5 predefined entity references in XML:
• ;&lt <  less than
• &gt; > greater than
• &amp; & ampersand 
• &apos; ‘ apostrophe
• &quot; “quotation mark
• Comments in XML
• The syntax for writing comments in XML is similar to that of
HTML.
• <!-- This is a comment -->
• What is an XML Element?
• An XML element is everything from (including) the element's
start tag to (including) the element's end tag.
• An element can contain:
• other elements
• text
• attributes
• or a mix of all of the above...
• <bookstore>
  <book category="CHILDREN">
    <title>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="WEB">
    <title>Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>
• In the example above, <bookstore> and <book> have element
contents, because they contain other elements. <book> also
has an attribute (category="CHILDREN"). <title>, <author>,
<year>, and <price> have text content because they contain
text.
• XML Naming Rules
• XML elements must follow these naming rules:
• Names can contain letters, numbers, and other characters
• Names cannot start with a number or punctuation character
• Names cannot start with the letters xml (or XML, or Xml, etc)
• Names cannot contain spaces
• Any name can be used, no words are reserved.
• Best Naming Practices
• Make names descriptive. Names with an underscore
separator are nice: <first_name>, <last_name>.
• Names should be short and simple, like this: <book_title> not
like this: <the_title_of_the_book>.
• Avoid "-" characters. If you name something "first-name,"
some software may think you want to subtract name from
first.
• Avoid "." characters. If you name something "first.name,"
some software may think that "name" is a property of the
object "first."
• XML Attributes Must be Quoted
• Attribute values must always be quoted. Either single or
double quotes can be used. For a person's sex, the person
element can be written like this:
• <person sex="female">
• or like this:
• <person sex='female'>
• If the attribute value itself contains double quotes you can use
single quotes, like in this example:
• <gangster name='George "Shotgun" Ziegler'>
• or you can use character entities:
• <gangster name="George &quot;Shotgun&quot; Ziegler">
• Avoid XML Attributes?
• Some of the problems with using attributes are:
• attributes cannot contain multiple values (elements can)
• attributes cannot contain tree structures (elements can)
• attributes are not easily expandable (for future changes)
• Attributes are difficult to read and maintain. Use elements for
data. Use attributes for information that is not relevant to the
data.
• Don't end up like this:
• <note day="10" month="01" year="2008"
to="Tove" from="Jani" heading="Reminder"
body="Don't forget me this weekend!">
</note>
• XML Elements vs. Attributes
• Take a look at these examples:
• <person sex="female">
  <firstname>Anna</firstname>
  <lastname>Smith</lastname>
</person>
•  
• <person>
  <sex>female</sex>
  <firstname>Anna</firstname>
  <lastname>Smith</lastname>
</person>
• In the first example sex is an attribute. In the last, sex is an element.
Both examples provide the same information.
• There are no rules about when to use attributes or when to use
elements. Attributes are handy in HTML.
• In XML my advice is to avoid them. Use elements instead.
• XML Attributes for Metadata
• Sometimes ID references are assigned to elements. These IDs can be used
to identify XML elements in much the same way as the id attribute in
HTML. This example demonstrates this:
• <messages>
  <note id="501">
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
  </note>
  <note id="502">
    <to>Jani</to>
    <from>Tove</from>
    <heading>Re: Reminder</heading>
    <body>I will not</body>
  </note>
</messages>
• Generating XML
• Just as PHP can be used to generate dynamic HTML, it can
also be used to generate dynamic XML.
• Generating an XML document from a PHP script is simple.
Simply change the MIME type of the document, using the
header( ) function, to "text/xml". To emit the <?xml... ?>
declaration without it being interpreted as a malformed PHP
tag,
• <?php header('Content-Type: text/xml'); ?>
• <?xml version='1.0' encoding='ISO-8859-1' ?>
• <?php
• header('content-type:text/xml');
• echo "<?xml version='1.0' encoding='ISO-8859-1'?>";
• echo"<Bookstore>";
• echo"<Books>";
• $ar=array(array("Programing php","OReally"),array("Beg PHp","Wrox"));
• for($i=0;$i<count($ar);$i++)
• {
• echo "<PHP>";
• echo"<Title>";
• echo $ar[$i][0];
• echo"</Title>";
• echo"<Pub>";
• echo $ar[$i][1];
• echo"</Pub>";
• echo"</PHP>";
• }
• echo"</Books>";
• echo"</Bookstore>";
• ?> (slip23)
• PHP SimpleXML - Read From String
• The PHP simplexml_load_string() function is used to read XML data
from a string.
• <?php
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";

$xml=simplexml_load_string($myXMLData) or die("Error: Cannot create


object");
print_r($xml);
?>
• The simplexml_load_file() function converts the specified XML
file into a SimpleXMLElement object.
• simplexml_load_file(file,classname,options,ns,is_prefix);

• Another example slip number 25 and 4.xml


• PHP XML
• XML Parsing
• To read and update - create and manipulate - an XML
document, we will need an XML parser.
• A parser is a piece of program that takes a physical
representation of some data and converts it into an in-
memory form for the program as a whole to use. Parsers are
used everywhere in software. 
• All major browsers have a built-in XML parser to access and
manipulate XML.
• There are two basic types of XML parsers:
• Tree-based parser: This parser transforms an XML document
into a tree structure. It analyzes the whole document, and
provides access to the tree elements
• Event-based parser: Views an XML document as a series of
events. When a specific event occurs, it calls a function to
handle it.
• The XML DOM (Document Object Model) defines the
properties and methods for accessing and editing XML.
• However, before an XML document can be accessed, it must
be loaded into an XML DOM object.
• The DOM parser is an tree-based parser.
• Example:
• <?xml version="1.0" encoding="ISO-8859-1"?>
<from>Jani</from>
• The XML DOM sees the XML above as a tree structure:
• Level 1: XML Document
• Level 2: Root element: <from>
• Level 3: Text element: "Jani"
• Functions of XML
• 1)xml_parser_create()
• This is used to create an xml parser which can be used with
the other xml functions for reading and writing data, getting
errors.
• 2) Xml_parse_into_struct(): xml data into an array
• 3)xml_error_string(): Get xml error string
• The XML file below will be used in our example:
• <?xml version=‘1.0’?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
• /* note.xml*/
• <?php
• $file=’note.xml’;
• $xpar=xml_parser_create();
• $fp=fopen($file,’r’);
• $xdata=fread($fp,4000);
• Xml_paeser_into_struct($spar,$xdata,$val);
• Xml_parser_free($xpar);
• Print_r($val);
• ?>
• /* save as .php
PHP and XML:

• XML and PHP can be combined to build web applications.


• It includes detailed explanation of PHP’s XML extensions,
together with illustrations of using PHP to parse, validate and
transform XML mark-up ,traverse XML data trees, exchange
data between web applications, overlays remote procedure
calls over HTTP and use free open source tools to add new
capabilities to our XML/PHP applications
• <html>
• <body>
• <form action="demoxml.php" method="POST">
• root element <input type="text" name="start">
• element name <input type="text" name="ename">
• attribute name <input type="text" name="evalue">
• <input type="submit" name="cmdbutton" value="create">
• <input type="hidden" name="hidden" value="true">
• </form>
• </body>
• </html>
• <?php
• if(isset($_POST['hidden']))
• { echo "Links Data Posted";

• $start = $_POST['start'];
• $ename = $_POST['ename'];
• $evalue = $_POST['evalue'];
• $xmlBeg = "<?xml version='1.0' encoding='ISO-8859-1'?>";
• $rootELementStart = "<$start>";
• $rootElementEnd = "</$start>";
• $xml_document= $xmlBeg;
• $xml_document .= $rootELementStart;
• $xml_document .= "<fname>";
• $xml_document .= $ename;
• $xml_document .= "</fname>";
• $xml_document .= "<sname>";
• $xml_document .= $evalue;
• $xml_document .= "</sname>";
• $xml_document .= $evalue;
• $xml_document .= $rootElementEnd;
• $file .= $start.".xml";
• $fp = fopen($file,'w');
• $write = fwrite($fp,$xml_document);
• echo "<br> THE LOaded file is <br>" .$file. "<br>";
• }
• ?>
• What is DOM(Document Object Model)?
• The W3C DOM provides a standard set of objects for HTML
and XML documents, and a standard interface for accessing
and manipulating them.
• The W3C DOM is separated into different parts (Core, XML,
and HTML) and different levels (DOM Level 1/2/3):
•  Core DOM - defines a standard set of objects for any
structured document
• XML DOM - defines a standard set of objects for XML
documents
• HTML DOM - defines a standard set of objects for HTML
documents
• Load and Output XML
• <?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");

print $xmlDoc->saveXML();
?>
• The output of the code above will be:
• Tove Jani Reminder Don't forget me this weekend
• If you select "View source" in the browser window, you will
see the following HTML:
• <?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
• The example above creates a DOMDocument-Object and
loads the XML from "note.xml" into it.
• The XML DOM(XML Document Object Model) :
• The XML DOM defines a standard way for accessing and
manipulating XML documents.
• PHP DOMs functions
• i.domxml_new_doc(): to create new XML document.
•  
• ii.domxml_open_file(): to open an XML document file as a DOM
object.
• iv. create_child(): creates new element.
•  
• v. append_child(): Which appends an element as a child of an
existing element.
•  
• Vi DomDocument->get_elements_by_tagname: Returns array with
nodes with given tagname in document or empty array,if not found.
• <book>
• <title>
• <year>
• </year>
• </title>
• </book>
• Calling:
• $domobj->get_elements_by_tagname(“title”);
• The Node Object
• The Node object represents a single node in the document
tree.
• A node can be an element node, an attribute node, a text
node, or any other of the node
• Get an Element Value
• The getElementsByTagName() method returns a node list
containing all elements with the specified tag name in the
same order as they appear in the source document.
• xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0];
• Get the Value of an Attribute
• In the DOM, attributes are nodes. Unlike element nodes, attribute
nodes have text values.
• The way to get the value of an attribute, is to get its text value.
• This can be done using the getAttribute() method or using the
nodeValue property of the attribute node.
• Get an Attribute Value - getAttribute()
• The getAttribute() method returns an attribute value.
• The following code retrieves the text value of the "lang" attribute of
the first <title> element:
• Example
• xmlDoc=loadXMLDoc("books.xml");

txt=xmlDoc.getElementsByTagName("title")[0].getAttribute("lang");
• Result:  txt = "en"
• Get an Attribute Value - getAttributeNode()
• The getAttributeNode() method returns an attribute node.
• The following code retrieves the text value of the "lang"
attribute of the first <title> element:
• Example
• xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")
[0].getAttributeNode("lang");
txt=x.nodeValue;
• Result:  txt = "en"

You might also like