XML Basics

in #steemstem7 years ago

XML

<h2>Introduction <ul> <li>XML stands for eXtensible Markup Language <li>XML tags are not predefined in XML. You must define your own tags. (And hence it is Extensible) <li>XML was designed to describe, store and transport data. <li>While storing it can be taken as alternative of database systems. <li>XML is a markup language much like HTML <li>XML was designed to be both human- and machine-readable. <li>XML was designed to be self-descriptive <li>XML is often used for distributing data over the Internet. <li>Platform independent <li>XML uses a DTD (Document Type Definition) to formally describe the data. <li>XML documents are formed as element trees. <h2>XML vs HTML <ul> <li>XML is not a replacement for HTML. XML and HTML were designed with different goals: <li>XML was designed to describe data and to focus on what data is. HTML was designed to display data and to focus on how data looks. <li>HTML is about displaying information, XML is about describing information. <h3>Example 1 <pre><code><?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> <h3>Syntax & Rules <ul> <li>XML file should start with XML <code>Prolog i.e. <code><?xml version="1.0" encoding="UTF-8"?>. This is optional but if added, should go on top. <li>To use international/unicode characters use encoding as <code>UTF-8 <li>All XML documents must have a root tag <li>All XML elements must have a closing tag <li>XML tags are case sensitive, XML tags are case sensitive. The tag <code><Apple> is different from the tag <code><apple> <li>All XML elements must be properly nested, <code><b><i>This text is bold and italic</b></i> <li>Attribute values must always be quoted <code><note date=12/11/99>, <code><note date="12/11/99"> <li>Special characters should be in Entity References. Like <code>< should be <code>&lt; <pre><code>&lt; < less than &gt; > greater than &amp; & ampersand &apos; ' apostrophe &quot; " quotation mark <ul> <li>Comments are written like in HTML <code>(html comment removed: This is a comment ) <li>White-space is Preserved in XML <p dir="auto">XML documents that conform to the syntax rules above are said to be "Well Formed" XML documents. <h3>XML Elements : <p dir="auto">An XML element is everything from (including) the element's start tag to (including) the element's end tag. <p dir="auto">An element can contain: <ul> <li>text <li>attributes <li>other elements <li>or a mix of the above <h4>XML Naming Rules <ul> <li>Are case-sensitive <li>Must start with a letter or underscore <li>Cannot start with the letters xml (or XML, or Xml, etc) <li>Can contain letters, digits, hyphens, underscores, and periods <li>Cannot contain spaces <h3>Example 2 <pre><code><?xml version="1.0" encoding="UTF-8"?> <breakfast_menu> <food> <name>Belgian Waffles</name> <price>$5.95</price> <description> Two of our famous Belgian Waffles with plenty of real maple syrup </description> <calories>650</calories> </food> <food> <name>Strawberry Belgian Waffles</name> <price>$7.95</price> <description> Light Belgian waffles covered with strawberries and whipped cream </description> <calories>900</calories> </food> <food> <name>Homestyle Breakfast</name> <price>$6.95</price> <description> Two eggs, bacon or sausage, toast, and our ever-popular hash browns </description> <calories>950</calories> </food> </breakfast_menu> <ul> <li>This example contains multiple nodes i.e. repeatative data like Food menu as <code><food> <h2>XML Attributes <ul> <li>XML attributes are normally used to describe XML elements, or to provide additional information about elements <li>Attributes are always contained within the start tag of an element. <code><person id="3344"> <li>Use of Elements vs. Attributes <code><person sex="female"> or <code><person><sex>female</sex></person> <li>There are no fixed rules about when to use attributes to describe data, and when to use elements. <li>Use attributes when you are sure that there won't be any repeatative values for certain data/values. <h2>XML Namespaces <ul> <li>XML Namespaces provide a method to avoid element name conflicts. <li>With prefixing a namespace with element, conflict can be avoided i.e. <code><namespace:element_name> <li>A namespace has to be defined prior to use in opening element tag using <code>xmlns attribute i.e. <code><namespace:element_name xmlns="some_url"> <h3>XML Namespaces - The xmlns Attribute <ul> <li>When using prefixes in XML, a namespace for the prefix must be defined. <li>The namespace can be defined by an xmlns attribute in the start tag of an element. <li>The namespace declaration has the following syntax. xmlns:prefix="URI". <li>Namespaces can also be declared in the XML root element <pre><code><root xmlns:h="http://www.w3.org/TR/html4/" xmlns:f="https://www.w3schools.com/furniture"> <ul> <li>The purpose of using an URI is to give the namespace a unique name. <li>Default Namespaces defining without name but it has to be unique <pre><code><table xmlns="namespaceURI"> <h2>CDATA vs PCDATA <h3>CDATA <p dir="auto">CDATA: (Unparsed Character data): CDATA contains the text which is not parsed further in an XML document. Tags inside the CDATA text are not treated as markup and entities will not be expanded. <pre><code><?xml version="1.0"?> <employee> <![CDATA[ <firstname>vimal</firstname> <lastname>jaiswal</lastname> <email>vimal@javatpoint.com</email> ]]> </employee> <p dir="auto">Output: <pre><code><firstname>vimal</firstname> <lastname>jaiswal</lastname> <email>vimal@javatpoint.com</email> <h3>PCDATA <p dir="auto">PCDATA: (Parsed Character Data): XML parsers are used to parse all the text in an XML document. PCDATA stands for Parsed Character data. PCDATA is the text that will be parsed by a parser. Tags inside the PCDATA will be treated as markup and entities will be expanded. <p dir="auto">In other words you can say that a parsed character data means the XML parser examine the data and ensure that it doesn't content entity if it contains that will be replaced. <h2>XML Schema <ul> <li><p dir="auto">Known as XML Schema Definition (XSD) <li><p dir="auto">Defines the elements, attributes and data types <li><p dir="auto">Describes and validates the structure and the content of XML data <li><p dir="auto">An XML Schema describes the structure of an XML document <li><p dir="auto">An XML document with correct syntax is called "Well Formed". <li><p dir="auto">An XML document validated against an XML Schema is both "Well Formed" and "Valid". <h3>Definition Types <p dir="auto">You can define XML schema elements in the following ways − <h4>Simple Type <p dir="auto">Simple type element is used only in the context of the text. Some of the predefined simple types are: <code>xs:integer, xs:boolean, xs:string, xs:date. For example − <pre><code><xs:element name = "phone_number" type = "xs:int" /> <h4>Complex Type <p dir="auto">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 − <pre><code><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> <p dir="auto">In the above example, Address element consists of child elements. This is a container for other <code><xs:element> definitions, that allows to build a simple hierarchy of elements in the XML document. <h4>Global Types <p dir="auto">With the 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 follows − <pre><code><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> <p dir="auto">Now let us use this type in our example as follows − <pre><code><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> <p dir="auto">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. <h3>Attributes <p dir="auto">Attributes in XSD provide extra information within an element. Attributes have name and type property as shown below − <pre><code><xs:attribute name = "x" type = "y"/> <h3>XSD Restrictions/Facets <p dir="auto">Restrictions are used to define acceptable values for XML elements or attributes. Restrictions on XML elements are called facets. <h4>Restrictions on Values <p dir="auto">The following example defines an element called "age" with a restriction. The value of age cannot be lower than 0 or greater than 120: <pre><code><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> <h4>Restrictions on a Set of Values <pre><code><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> <p dir="auto">Above example defines an element called "car" with a restriction. The only acceptable values are: Audi, Golf, BMW <h3>Default and Fixed Values for Simple Elements <ul> <li>Simple elements may have a default value OR a fixed value specified. <li>A default value is automatically assigned to the element when no other value is specified. <li>In the following example the default value is "red": <pre><code><xs:element name="color" type="xs:string" default="red"/> <ul> <li>A fixed value is also automatically assigned to the element, and you cannot specify another value. <li>In the following example the fixed value is "red": <pre><code><xs:element name="color" type="xs:string" fixed="red"/> <h2>DTD <ul> <li>The XML Document Type Declaration, commonly known as DTD, is a way to describe XML language precisely. <li>DTDs check vocabulary and validity of the structure of XML documents against grammatical rules of appropriate XML language. <li>An XML DTD can be either specified inside the document, or it can be kept in a separate document and then liked separately. <li>An XML document with correct syntax is called <code>Well Formed. <li>An XML document validated against a DTD is both "Well Formed" and <code>Valid. <h3>Syntax of DTD <pre><code><!DOCTYPE element DTD identifier [ declaration1 declaration2 ........ ]> <ul> <li>The DTD starts with <code><!DOCTYPE delimiter. <li>An element tells the parser to parse the document from the specified root element. <li>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 External Subset. <li>The square brackets [ ] enclose an optional list of entity declarations called Internal Subset. <h3>Elements <p dir="auto">In a DTD, elements are declared with an ELEMENT declaration. <h4>Syntax <pre><code><!ELEMENT element-name category> or <!ELEMENT element-name (element-content)> <h4>Empty Elements <pre><code><!ELEMENT element-name EMPTY> <h4>Elements with Parsed Character Data <pre><code><!ELEMENT element-name (#PCDATA)> <p dir="auto">Example: <pre><code><!ELEMENT from (#PCDATA)> <h4>Elements with Children (sequences) <pre><code><!ELEMENT element-name (child1)> <!ELEMENT element-name (child1,child2,...)> <!ELEMENT note (to,from,heading,body)> <h4>Example <pre><code><!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> <h4>Declaring Minimum One Occurrence (<code>+) <pre><code><!ELEMENT element-name (child-name+)> <h4>Declaring Zero or More Occurrences (<code>*) <pre><code><!ELEMENT element-name (child-name*)> <h4>Declaring Mixed Content <pre><code><!ELEMENT note (#PCDATA|to|from|header|message)*> <h3>Attributes <p dir="auto">In a DTD, attributes are declared with an ATTLIST declaration. <h4>Syntax <pre><code><!ATTLIST element-name attribute-name attribute-type attribute-value> <h4>DTD example: <pre><code><!ATTLIST payment type CDATA "check"> <h4>XML example: <pre><code><payment type="check" /> <h4>attribute-value <p dir="auto"><code>value - The default value of the attribute<br /> <code>#REQUIRED - The attribute is required<br /> <code>#IMPLIED - The attribute is optional<br /> <code>FIXED - The attribute value is fixed <h4>attribute-type <p dir="auto"><code>CDATA - The value is character data<br /> <code>(en1|en2|..) The value must be one from an enumerated list<br /> <code>ID The value is a unique id<br /> <code>IDREF The value is the id of another element<br /> <code>IDREFS The value is a list of other ids<br /> <code>NMTOKEN The value is a valid XML name<br /> <code>NMTOKENS The value is a list of valid XML names<br /> <code>ENTITY The value is an entity<br /> <code>ENTITIES The value is a list of entities<br /> <code>NOTATION The value is a name of a notation<br /> <code>xml: The value is a predefined xml value <h4>Example <ul> <li>DTD: <pre><code><!ELEMENT square EMPTY> <!ATTLIST square width CDATA "0"> <ul> <li>Valid XML: <pre><code><square width="100" /> <p dir="auto">In the example above, the "square" element is defined to be an empty element with a "width" attribute of type CDATA. If no width is specified, it has a default value of 0. <h3>Internal DTD <p dir="auto">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 an external source. <h4>Syntax <p dir="auto">Following is the syntax of internal DTD − <pre><code><!DOCTYPE root-element [element-declarations]> <p dir="auto">Where <code>root-element is the name of root element and element-declarations is where you declare the elements. <h4>Example <pre><code><?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>Rohit Sharma</name> <company>Swastik Collge</company> <phone>9841000000</phone> </address> <h4>Rules <ul> <li>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 the document. <li>Similar to the DOCTYPE declaration, the element declarations must start with an exclamation mark. <li>The Name in the document type declaration must match the element type of the root element. <h3>External DTD <p dir="auto">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 external source. <h4>Syntax <p dir="auto">Following is the syntax for external DTD − <pre><code><!DOCTYPE root-element SYSTEM "file-name"> <p dir="auto">Where file-name is the file with .dtd extension. <h4>Example <pre><code><?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?> <!DOCTYPE address SYSTEM "address.dtd"> <address> <name>Rohit Sharma</name> <company>Swastik Collge</company> <phone>9841000000</phone> </address> <p dir="auto">The content of the DTD file <code>address.dtd is as shown − <pre><code><!ELEMENT address (name,company,phone)> <!ELEMENT name (#PCDATA)> <!ELEMENT company (#PCDATA)> <!ELEMENT phone (#PCDATA)> <h3>System Identifiers <p dir="auto">A system identifier enables you to specify the location of an external file containing DTD declarations. Syntax is as follows − <p dir="auto"><code><!DOCTYPE name SYSTEM "address.dtd" [...]> <p dir="auto">As you can see, it contains keyword <code>SYSTEM and a URI reference pointing to the location of the document. <h3>Public Identifiers <p dir="auto">Public identifiers provide a mechanism to locate DTD resources and is written as follows − <p dir="auto"><code>-<!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN"> <p dir="auto">As you can see, it begins with keyword <code>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. <h2>When to Use a DTD/Schema? <ul> <li>With a DTD, independent groups of people can agree to use a standard DTD for interchanging data. <li>With a DTD, you can verify that the data you receive from the outside world is valid. <li>You can also use a DTD to verify your own data. <h2>XPath <ul> <li>XPath is an important and core component of XSLT standard. It is used to traverse the elements and attributes in an XML document. <li>XPath is a W3C recommendation. XPath provides different types of expressions to retrieve relevant information from the XML document. It is syntax for defining parts of an XML document. <h3>Important features of XPath <ul> <li>XPath defines structure: XPath is used to define the parts of an XML document i.e. element, attributes, text, namespace, processing-instruction, comment, and document nodes. <li>XPath provides path expression: XPath provides powerful path expressions, select nodes, or list of nodes in XML documents. <li>XPath is a core component of XSLT: XPath is a major element in XSLT standard and must be followed to work with XSLT documents. <li>XPath is a standard function: XPath provides a rich library of standard functions to manipulate string values, numeric values, date and time comparison, node and QName manipulation, sequence manipulation, Boolean values etc. <li>Path is W3C recommendation. <h3>Nodes <p dir="auto">XPath specifies seven types of nodes that can be output of the execution of the XPath expression. <ul> <li>Root <li>Element <li>Text <li>Attribute <li>Comment <li>Processing Instruction <li>Namespace <pre><code>Index Expression Description 1) node-name It is used to select all nodes with the given name "nodename" 2) / It specifies that selection starts from the root node. 3) // It specifies that selection starts from the current node that match the selection. 4) . Select the current node. 5) .. Select the parent of the current node. 6) @ Selects attributes. 7) student Example - selects all nodes with the name `student`. 8) class/student Example - selects all student elements that are children of class 9) //student Selects all student elements no matter where they are in the document <h2>XSLT <h3>XSL <p dir="auto">XSL stands for EXtensible Stylesheet Language. It is similar to XML as CSS is to HTML. In case of HTML document, tags are predefined such as table, div, and span; and the browser knows how to add style to them and display those using CSS styles. But in case of XML documents, tags are not predefined. In order to understand and style an XML document, World Wide Web Consortium (W3C) developed XSL which can act as XML based Stylesheet Language. An XSL document specifies how a browser should render an XML document. <h3>What is XSLT ? <p dir="auto">XSLT, Extensible Stylesheet Language Transformations, provides the ability to transform XML data from one format to another automatically. <p dir="auto">An XSLT stylesheet is used to define the transformation rules to be applied on the target XML document. XSLT stylesheet is written in XML format. XSLT Processor takes the XSLT stylesheet and applies the transformation rules on the target XML document and then it generates a formatted document in the form of XML, HTML, or text format. This formatted document is then utilized by XSLT formatter to generate the actual output which is to be displayed to the end-user. <h3>Advantages <ul> <li>Independent of programming. Transformations are written in a separate xsl file which is again an XML document. <li>Output can be altered by simply modifying the transformations in xsl file. No need to change any code. So Web designers can edit the stylesheet and can see the change in the output quickly. <h3>XSLT Document Syntax <p dir="auto">Syntax of .xsl file: <pre><code><?xml version = "1.0" encoding = "UTF-8"?> <xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"> <xsl:template match = "xpath"> (html comment removed: HTML tags Used for formatting purpose. Processor will skip them and browser will simply render them. ) <xsl:for-each select="xpath"> <xsl:value-of select = "xpath"/> </xsl:for-each> </xsl:template> </xsl:stylesheet> <p dir="auto">Now include/ink the xsl file into the XML <pre><code><?xml-stylesheet type = "text/xsl" href = "file.xsl"?> <p dir="auto"><code><?xml-stylesheet tag is used to import the XSL file into the XML file with <code>type=text/xsl and <code>href=file.xsl attributes. <h3>Example <h4>students.xsl <pre><code><?xml version = "1.0" encoding = "UTF-8"?> <xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"> <xsl:template match = "/"> <html> <body> <h2>Students</h2> <table border = "1"> <tr bgcolor = "#9acd32"> <th>Roll No</th> <th>First Name</th> <th>Last Name</th> <th>Nick Name</th> <th>Marks</th> </tr> <xsl:for-each select="class/student"> <xsl:sort select = "firstname"/> <xsl:if test = "marks > 90"> <tr> <td> <xsl:value-of select = "@rollno"/> </td> <td><xsl:value-of select = "firstname"/></td> <td><xsl:value-of select = "lastname"/></td> <td><xsl:value-of select = "nickname"/></td> <td><xsl:value-of select = "marks"/></td> </tr> </xsl:if> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> <h4>students.xml <pre><code><?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "students.xsl"?> <class> <student rollno="393"> <firstname>Ram</firstname> <lastname>Sharma</lastname> <nickname>Ram</nickname> <marks>85</marks> </student> <student rollno="493"> <firstname>Rohit</firstname> <lastname>Yadav</lastname> <nickname>Rohit</nickname> <marks>95</marks> </student> <student rollno="593"> <firstname>Shishir</firstname> <lastname>Gautam</lastname> <nickname>Sisi</nickname> <marks>90</marks> </student> </class> <h4><xsl:template> <p dir="auto">Defines a way to reuse templates in order to generate the desired output for nodes of a particular type/context. <h4><xsl:template> <p dir="auto">Defines a way to reuse templates in order to generate the desired output for nodes of a particular type/context. <h4><xsl:value-of> <p dir="auto">Tag puts the value of the selected node as per XPath expression, as text. <h4><xsl:for-each> <p dir="auto">Tag applies a template repeatedly for each node. <h4><xsl:sort> <p dir="auto">Tag specifies a sort criteria on the nodes. <h4>< message> <p dir="auto">Tag element helps to debug an XSLT processing. It is similar to javascript alerts. <xsl:> tag buffers a message to XSLT processor which terminates the processing and sends a message to the caller application to display the error message. <pre><code><xsl:if test = "firstname = ''"> <xsl:message terminate = "yes">A first name field is empty. </xsl:message> </xsl:if> <h4><xsl:choose> <p dir="auto">Tag specifies a multiple conditional tests against the content of nodes in conjunction with the <xsl:otherwise> and <xsl:when> elements. <pre><code><xsl:choose> <xsl:when test = "marks > 90"> High </xsl:when> <xsl:when test = "marks > 85"> Medium </xsl:when> <xsl:otherwise> Low </xsl:otherwise> </xsl:choose> <h2>DOM <ul> <li>The Document Object Model (DOM) is the foundation of XML. XML documents have a hierarchy of informational units called nodes; DOM is a way of describing those nodes and the relationships between them. <li>A DOM document is a collection of nodes or pieces of information organized in a hierarchy. 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. <li>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. <li>Understanding the DOM is a must for anyone working with HTML or XML. <li>The XML DOM makes a tree-structure view for an XML document. <li>We can access all elements through the DOM tree. <li>We can modify or delete their content and also create new elements. The elements, their content (text and attributes) are all known as nodes. <p dir="auto"><code>book.xml <pre><code><?xml version="1.0" encoding="UTF-8"?> <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> </bookstore> <pre><code>txt = xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue; <p dir="auto">And following <code>book.html example loads a text string into an XML DOM object <code>book.xml, and extracts the info from it with JavaScript: <pre><code><!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var xmlDoc = this.responseXML; var p = document.getElementById("demo"); var titles = xmlDoc.getElementsByTagName("title"); var titlesHtml = '<ul>'; for(var i = 0; i < titles.length; i++){ var cat = titles[i].parentNode.getAttribute('category'); titlesHtml += "<li>" + titles[i].childNodes[0].nodeValue + " (" + cat +")</li>"; } titlesHtml += '</ul>'; p.innerHTML = titlesHtml; } }; xhttp.open("GET", "book.xml", true); xhttp.send(); function myFunction(xml) { var xmlDoc = xml.responseXML; document.getElementById("demo").innerHTML = xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue; } </script> </body> </html> <h3>DOM Parser <h4>Parsing XML Text String <ul> <li>The XML DOM (Document Object Model) defines the properties and methods for accessing and editing XML. <li>However, before an XML document can be accessed, it must be loaded into an XML DOM object. <li>All modern browsers have a built-in XML parser that can convert text into an XML DOM object. <p dir="auto">This example parses a text string into an XML DOM object, and extracts the info from it with JavaScript: <p dir="auto"><code>load_string.html <pre><code><html> <body> <p id="demo"></p> <script> var text, parser, xmlDoc; text = "<bookstore><book>" + "<title>Everyday Italian</title>" + "<author>Giada De Laurentiis</author>" + "<year>2005</year>" + "</book></bookstore>"; parser = new DOMParser(); xmlDoc = parser.parseFromString(text,"text/xml"); document.getElementById("demo").innerHTML = xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue; </script> </body> </html> <h3>XML DOM Properties <p dir="auto">These are some typical DOM properties: <ul> <li>x.nodeName - the name of x <li>x.nodeValue - the value of x <li>x.parentNode - the parent node of x <li>x.childNodes - the child nodes of x <li>x.attributes - the attributes nodes of x <h3>XML DOM Methods <ul> <li>x.getElementsByTagName(name) - get all elements with a specified tag name <li>x.appendChild(node) - insert a child node to x <li>x.removeChild(node) - remove a child node from x <p dir="auto"><code>Note: In the list above, x is a node object. <h3>Nodes <ul> <li>Text is Always Stored in Text Nodes <li>The XML DOM views an XML document as a tree-structure. The tree structure is called a node-tree. <h3>Node Parents, Children, and Siblings <ul> <li>In a node tree, the top node is called the <code>root <li>Every node, except the root, has exactly one <code>parent node <li>A node can have any number of <code>children <li>A leaf is a node with <code>no children <li><code>Siblings are nodes with the same parent <h3>XML DOM Get Node Values <ul> <li>The <code>nodeValue property is used to get the text value of a node. <li>The <code>getAttribute('attribute_name') method returns the value of an attribute. <pre><code>x = xmlDoc.getElementsByTagName("title")[0]; txt = x.getAttribute("lang"); <h3>Create a node <pre><code>newElement = xmlDoc.createElement("edition"); <h3>Add a Node - appendChild() <pre><code>newEle = xmlDoc.createElement("edition"); xmlDoc.getElementsByTagName("book")[0].appendChild(newEle); <h2>XQuery <p dir="auto">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. XQuery is replacing complex Java or C++ programs with a few lines of code. XQuery is simpler to work with and easier to maintain than many other alternatives. <ul> <li><strong>Functional Language − XQuery is a language to retrieve/querying XML based data. <li><strong>Analogous to SQL − XQuery is to XML what SQL is to databases. <li><strong>XPath based − XQuery uses XPath expressions to navigate through XML documents. <li><strong>Universally accepted − XQuery is supported by all major databases. <li><strong>W3C Standard − XQuery is a W3C standard. <h3>Benefits of XQuery <ul> <li>Using XQuery, both hierarchical and tabular data can be retrieved. <li>XQuery can be used to query tree and graphical structures. <li>XQuery can be directly used to query webpages. <li>XQuery can be directly used to build webpages. <li>XQuery can be used to transform xml documents. <li>XQuery is ideal for XML-based databases and object-based databases. Object databases are much more flexible and powerful than purely tabular databases.