Языки описания информации Лекция ХХХ. Кафедра «ОСУ» Весенний семестр 2010/2011 уч. года Программирование работы с XML документами.

Презентация:



Advertisements
Похожие презентации
Using Dreamweaver MX Slide 1 Window menu Manage Sites… Window menu Manage Sites… 2 2 Open Dreamweaver 1 1 Set up a website folder (1). Click New…
Advertisements

1/27 Chapter 9: Template Functions And Template Classes.
S4-1 PAT328, Section 4, September 2004 Copyright 2004 MSC.Software Corporation SECTION 4 FIELD IMPORT AND EXPORT.
Inner Classes. 2 Simple Uses of Inner Classes Inner classes are classes defined within other classes The class that includes the inner class is called.
PAT312, Section 21, December 2006 S21-1 Copyright 2007 MSC.Software Corporation SECTION 21 GROUPS.
Lesson 3 - HTML Formatting. Text Formatting Tags TagDescription Defines bold text Defines big text Defines emphasized text Defines italic text Defines.
SPLAY TREE The basic idea of the splay tree is that every time a node is accessed, it is pushed to the root by a series of tree rotations. This series.
Carousel from flshow.netflshow.net by Saverio CaminitiSaverio Caminiti.
S11-1PAT301, Section 11, October 2003 SECTION 11 ANALYSIS SETUP.
Linux Daemons. Agenda What is a daemon What is a daemon What Is It Going To Do? What Is It Going To Do? How much interaction How much interaction Basic.
Java Server Pages(JSP). JavaServer Pages (JSP) позволяют вам отделить динамическую часть ваших страниц от статического HTML. Вы, как обычно, пишете обычный.
1 © Luxoft Training 2012 Inner and anonymous classes.
© 2005 Cisco Systems, Inc. All rights reserved.INTRO v Managing Your Network Environment Managing Cisco Devices.
Loader Design Options Linkage Editors Dynamic Linking Bootstrap Loaders.
© 2009 Avaya Inc. All rights reserved.1 Chapter Two, Voic Pro Components Module Two – Actions, Variables & Conditions.
AVL-Trees COMP171 Fall AVL Trees / Slide 2 Balanced binary tree * The disadvantage of a binary search tree is that its height can be as large as.
Running Commands & Getting Help. Running Commands Commands have the following syntax: command options arguments Each item is separated by a space Options.
DRAFTING and DIMENSIONING 98. A properly dimensioned drawing of a part is very important to the manufacturing outcome. With CATIA, it can be a very simple.
Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.
MOUSE MANIPULATION 23. The 3 button mouse is your tool for manipulation of the parts and assemblies that you have created. With it you can ZOOM, ROTATE.
Транксрипт:

Языки описания информации Лекция ХХХ. Кафедра «ОСУ» Весенний семестр 2010/2011 уч. года Программирование работы с XML документами

Document Object Model

Основные классы

Объектная модель XML документа

Объектная модель документа (DOM) представляет из себя не зависящий от платформы и языка программный интерфейс с помощью которого можно получать доступ к содержимому XML документов и изменять их. С помощью DOM XML документ может быть представлен в виде дерева узлов. Узлы собой элемент, атрибут, текстовый, графический или любой другой объект. Узлы дерева могут представлять элементы и другие части XML документа и связаны между собой отношением предок-потомок.

Пример XML документа Pro C# 2008 Troelsen Apress 01/11/2007 … …

Пример объектного представления document xml books book price pubinfo title Pro C# pubdate publisher 2008 apress author Troelsen book format dollar

Иерархия классов DOM для модели XML DOM W3C Node Document DocumentFragment Entity Notation Attr CharacterData Comment Text CDATAsection Element DocumentType EntityReference ProcessingInstruction DOMImplementation NodeList NamedNodeMap

Иерархия классов DOM в.NET XmlNode XmlDocument XmlDataDocument XmlDocumentFragment XmlEntity XmlNotation XmlAttribute XmllinkedNode XmlCharacterData XmlComment XmlText XmlCDATAsection XmlWhiteSpace XmlSignificantWhiteSpace XmlElement XmlDeclaration XmlDocumentType XmlEntityReference XmlProcessingInstruction XmlImplementation XmlNodeList XmlNamedNodeMap XmlAttributeCollection XmlNodeChangedEventArgs

Класс XmlNode public abstract class XmlNode : ICloneable, IEnumerable, IXPathNavigable { public virtual XmlNode AppendChild( XmlNode newChild ); public abstract XmlNode CloneNode( bool deep ); public virtual XmlNode InsertAfter( XmlNode newChild, XmlNode refChild ); public virtual XmlNode InsertBefore( XmlNode newChild, XmlNode refChild ); public virtual XmlNode PrependChild( XmlNode newChild ); public virtual void RemoveAll(); public virtual XmlNodeList ChildNodes { get; }; public abstract string Name { get; }; public virtual XmlNode NextSibling { get; }; public abstract XmlNodeType NodeType { get; }; public virtual XmlNode ParentNode { get; } public virtual XmlNode PreviousSibling { get; }; public virtual string Value { get; set; }; }

Методы и свойства класса XmlNode Метод или Свойство Назначение AppendChild Добавляет узел в конец списка дочерних узлов CloneNode Создаёт копию узла InsertAfter Вставляет заданный узел после указанного узла InsertBefore Вставляет заданный узел перед указанным узлом PrependChild Добавляет узел в начало списка дочерних узлов RemoveAll Удаляет все дочерние узлы и атрибуты ChildNodes Возвращает все дочерние узлы NextSibling Возвращает следующий узел Name Возвращает имя узла Value Возвращает или задает значение узла

Классы XmlLinkedNode и XmlElement Сетевые технологии 13 public class XmlElement : XmlLinkedNode { public virtual string GetAttribute(string name); public virtual XmlAttribute GetAttributeNode(string name); public virtual void RemoveAttribute(string name); public virtual void SetAttribute(string name, string value); public override XmlAttributeCollection Attributes { get; }; } public class XmlElement : XmlLinkedNode { public virtual string GetAttribute(string name); public virtual XmlAttribute GetAttributeNode(string name); public virtual void RemoveAttribute(string name); public virtual void SetAttribute(string name, string value); public override XmlAttributeCollection Attributes { get; }; } public class XmlLinkedNode : XmlNode { public override XmlNode NextSibling { get; }; public override XmlNode PreviousSibling { get; }; } public class XmlLinkedNode : XmlNode { public override XmlNode NextSibling { get; }; public override XmlNode PreviousSibling { get; }; }

Перечисление XmlNodeType Сетевые технологии 14 public enum XmlNodeType { None, Element, // элемент Attribute, // атрибут Text, // текст внутри элемента CDATA, // раздел CDATA EntityReference, Entity, ProcessingInstruction, Comment, // комментарий Document, // документ DocumentType, DocumentFragment, Notation, Whitespace, SignificantWhitespace, EndElement, EndEntity, XmlDeclaration // объявление XML } public enum XmlNodeType { None, Element, // элемент Attribute, // атрибут Text, // текст внутри элемента CDATA, // раздел CDATA EntityReference, Entity, ProcessingInstruction, Comment, // комментарий Document, // документ DocumentType, DocumentFragment, Notation, Whitespace, SignificantWhitespace, EndElement, EndEntity, XmlDeclaration // объявление XML }

Класс XmlDocument Сетевые технологии 15 public class XmlDocument : XmlNode { public XmlDocument(); public virtual void Load(string filename); public virtual void LoadXml(string xml); public virtual void Save(string filename); } public class XmlDocument : XmlNode { public XmlDocument(); public virtual void Load(string filename); public virtual void LoadXml(string xml); public virtual void Save(string filename); }

Методы класса XmlDocument Сетевые технологии 16 Метод Назначение Load Загружает XML документ LoadXml Загружает XML документ из строки Save Записывает XML документ

Использование объектной модели документа

Использование XML DOM Сетевые технологии 18 Использование объектной модели XML документа позволяет открыть файл считать документ в память, затем закрыть файл и работать с объектной моделью XML документа в памяти. После чего если были внесены изменения документ может быть записан на диск. При работе с объектной моделью документа в памяти доступ к документу может осуществляться в произвольном порядке.

Запись XML документа Сетевые технологии 19 static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml(" "); XmlElement book = doc.CreateElement("book"); XmlElement title = doc.CreateElement("title"); title.InnerText = ".NET Framework Programming"; XmlElement author = doc.CreateElement("author"); author.InnerText = "Jeffrey Richter"; XmlElement price = doc.CreateElement("price"); price.SetAttribute("format","euros"); price.InnerText="39.99"; book.AppendChild(title); book.AppendChild(author); book.AppendChild(price); doc.DocumentElement.AppendChild(book); doc.Save("books.xml"); } static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml(" "); XmlElement book = doc.CreateElement("book"); XmlElement title = doc.CreateElement("title"); title.InnerText = ".NET Framework Programming"; XmlElement author = doc.CreateElement("author"); author.InnerText = "Jeffrey Richter"; XmlElement price = doc.CreateElement("price"); price.SetAttribute("format","euros"); price.InnerText="39.99"; book.AppendChild(title); book.AppendChild(author); book.AppendChild(price); doc.DocumentElement.AppendChild(book); doc.Save("books.xml"); }

Получившийся XML документ Сетевые технологии 20. NET Framework Programming Jeffrey Richter NET Framework Programming Jeffrey Richter 39.99

Чтение XML документа Сетевые технологии 21 private static string ReadXML(XmlNodeList nodeList) { StringBuilder str = new StringBuilder(); foreach (XmlNode node in nodeList) { switch (node.NodeType) { case XmlNodeType.XmlDeclaration: str.AppendFormat("Объявление XML : {0} {1} \n", node.Name, node.Value); break; case XmlNodeType.Element: str.AppendFormat("Элемент: {0} \n",node.Name); break; case XmlNodeType.Text: str.AppendFormat(" Значение: {0} \n",node.Value); break; case XmlNodeType.Comment: str.AppendFormat("Комментарий: {0} \n", node.Value); break; }... } private static string ReadXML(XmlNodeList nodeList) { StringBuilder str = new StringBuilder(); foreach (XmlNode node in nodeList) { switch (node.NodeType) { case XmlNodeType.XmlDeclaration: str.AppendFormat("Объявление XML : {0} {1} \n", node.Name, node.Value); break; case XmlNodeType.Element: str.AppendFormat("Элемент: {0} \n",node.Name); break; case XmlNodeType.Text: str.AppendFormat(" Значение: {0} \n",node.Value); break; case XmlNodeType.Comment: str.AppendFormat("Комментарий: {0} \n", node.Value); break; }... }

Чтение XML документа (2) Сетевые технологии 22 private static string ReadXML(XmlNodeList nodeList) {... if (node.Attributes != null) { foreach (XmlAttribute attrib in node.Attributes) str.AppendFormat(" Атрибут: {0} Значение: {1} \n", attrib.Name, attrib.Value) } if (node.HasChildNodes) { str.Append(ReadXML(node.ChildNodes)); } return str.ToString(); } private static string ReadXML(XmlNodeList nodeList) {... if (node.Attributes != null) { foreach (XmlAttribute attrib in node.Attributes) str.AppendFormat(" Атрибут: {0} Значение: {1} \n", attrib.Name, attrib.Value) } if (node.HasChildNodes) { str.Append(ReadXML(node.ChildNodes)); } return str.ToString(); }

XML-документ, который представляет заказ покупателя в магазине музыкальных CD (test.xml) Dare Obasanjo One Microsoft Way Redmond WA Nelly Nellyville Baby D Lil Chopper Toy Если заказчика нет по указанному адресу, тогда попытайтесь оставить пакет в одном из следующих мест, список которых приведен в порядке приоритетности доставки Соседняя дверь У консьержа На пороге Примечание Не забудьте оставить записку с точным указанием, где находится пакет.

Чтение XML документа (3) Сетевые технологии 24 using System; using System.Xml; public class Test { public static void Main(string[] args) { XmlDocument doc = new XmlDocument(); doc.Load("test.xml"); XmlElement firstCD = (XmlElement) doc.DocumentElement.FirstChild; XmlElement artist = (XmlElement) firstCD.GetElementsByTagName("artist")[0]; XmlElement title = (XmlElement) firstCD.GetElementsByTagName("title")[0] Console.WriteLine("Artist={0}, Title={1}", artist.InnerText, title.InnerText); } using System; using System.Xml; public class Test { public static void Main(string[] args) { XmlDocument doc = new XmlDocument(); doc.Load("test.xml"); XmlElement firstCD = (XmlElement) doc.DocumentElement.FirstChild; XmlElement artist = (XmlElement) firstCD.GetElementsByTagName("artist")[0]; XmlElement title = (XmlElement) firstCD.GetElementsByTagName("title")[0] Console.WriteLine("Artist={0}, Title={1}", artist.InnerText, title.InnerText); }

Последовательный доступ к XML документу Сетевые технологии

Использование последовательного доступа Сетевые технологии 26 Последовательный доступ к XML документам позволяет читать и записывать их наиболее эффективно. Недостатками использования этого подхода являются то, что во-первых доступ осуществляется линейно, а во-вторых во время работы с документом файл остаётся открытым.

Класс XmlTextWriter Сетевые технологии 27 public class XmlTextWriter : XmlWriter { public void WriteAttributeString(string localName, string value); public override void WriteComment(string text); public override void WriteEndDocument(); public override void WriteEndElement(); public override void WriteStartDocument(); public void WriteStartElement(string localName); } public class XmlTextWriter : XmlWriter { public void WriteAttributeString(string localName, string value); public override void WriteComment(string text); public override void WriteEndDocument(); public override void WriteEndElement(); public override void WriteStartDocument(); public void WriteStartElement(string localName); }

Методы класса XmlTextWriter Сетевые технологии 28 Метод Назначение WriteAttributeString Записывает атрибут WriteComment Записывает комментарий WriteEndDocument Закрывает все открытые элементы или атрибуты WriteEndElement Закрывает открытый элемент WriteStartDocument Записывает объявление XML WriteStartElement Записывает открывающий тег

Класс XmlTextReader Сетевые технологии 29 public class XmlTextReader : XmlReader, IXmlLineInfo, IXmlNamespaceResolver { public override bool Read(); public virtual void ReadEndElement(); public virtual void ReadStartElement(); public override string ReadString(); public virtual bool HasAttributes { get; } public override string Name { get; } public override string Value { get; } } public class XmlTextReader : XmlReader, IXmlLineInfo, IXmlNamespaceResolver { public override bool Read(); public virtual void ReadEndElement(); public virtual void ReadStartElement(); public override string ReadString(); public virtual bool HasAttributes { get; } public override string Name { get; } public override string Value { get; } }

Методы и свойства класса XmlTextReader Сетевые технологии 30 Метод или Свойство Назначение Read Считывает узел ReadEndElement Проверяет что текущий узел закрывающий тег и переходит к следующему узлу ReadStartElement Проверяет что текущий узел элемент и переходит к следующему узлу ReadString Возвращает содержимое элемента или текстового узла HasAttributes Определяет есть ли атрибуты у узла Name Возвращает имя узла Value Возвращает значение узла

Запись XML документа Сетевые технологии 31 static void Main() { XmlTextWriter writer = new XmlTextWriter("books.xml", null); writer.Formatting = Formatting.Indented; writer.Indentation = 3; writer.WriteStartDocument(); writer.WriteComment("Создан: " + DateTime.Now.ToString()); writer.WriteStartElement("books"); writer.WriteStartElement("book"); writer.WriteElementString("title", "CLR via C#"); writer.WriteElementString("author", "Jeffrey Richter"); writer.WriteStartElement("price"); writer.WriteAttributeString("format", "dollars"); writer.WriteString("59.99"); writer.WriteEndElement(); writer.WriteStartElement("pubinfo"); writer.WriteElementString("publisher", "Microsoft Press"); writer.WriteElementString("pubdate", "22/03/2006"); writer.WriteEndElement(); writer.Close(); } static void Main() { XmlTextWriter writer = new XmlTextWriter("books.xml", null); writer.Formatting = Formatting.Indented; writer.Indentation = 3; writer.WriteStartDocument(); writer.WriteComment("Создан: " + DateTime.Now.ToString()); writer.WriteStartElement("books"); writer.WriteStartElement("book"); writer.WriteElementString("title", "CLR via C#"); writer.WriteElementString("author", "Jeffrey Richter"); writer.WriteStartElement("price"); writer.WriteAttributeString("format", "dollars"); writer.WriteString("59.99"); writer.WriteEndElement(); writer.WriteStartElement("pubinfo"); writer.WriteElementString("publisher", "Microsoft Press"); writer.WriteElementString("pubdate", "22/03/2006"); writer.WriteEndElement(); writer.Close(); }

Получившийся XML документ Сетевые технологии 32 CLR via C# Jeffrey Richter Microsoft Press 22/03/2006 CLR via C# Jeffrey Richter Microsoft Press 22/03/2006

Чтение XML документа (начало) Сетевые технологии 33 static void Main() { XmlTextReader reader = new XmlTextReader("books.xml"); StringBuilder str = new StringBuilder(); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.XmlDeclaration: str.AppendFormat("Объявление XML : {0} {1} \n", reader.Name,reader.Value); break; case XmlNodeType.Element: str.AppendFormat("Элемент: {0} \n",reader.Name); break; case XmlNodeType.Text: str.AppendFormat(" Значение: {0} \n",reader.Value); break; case XmlNodeType.Comment: str.AppendFormat("Комментарий: {0} \n,reader.Value); break;... }... } static void Main() { XmlTextReader reader = new XmlTextReader("books.xml"); StringBuilder str = new StringBuilder(); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.XmlDeclaration: str.AppendFormat("Объявление XML : {0} {1} \n", reader.Name,reader.Value); break; case XmlNodeType.Element: str.AppendFormat("Элемент: {0} \n",reader.Name); break; case XmlNodeType.Text: str.AppendFormat(" Значение: {0} \n",reader.Value); break; case XmlNodeType.Comment: str.AppendFormat("Комментарий: {0} \n,reader.Value); break;... }... }

Чтение XML документа (продолжение) Сетевые технологии 34 static void Main() {... if (reader.AttributeCount > 0) { while (reader.MoveToNextAttribute()) str.AppendFormat(" Атрибут: {0} Значение: {1} \n", reader.Name, reader.Value); } reader.Close(); Console.WriteLine(str); } static void Main() {... if (reader.AttributeCount > 0) { while (reader.MoveToNextAttribute()) str.AppendFormat(" Атрибут: {0} Значение: {1} \n", reader.Name, reader.Value); } reader.Close(); Console.WriteLine(str); }

Курсорные API Курсорные API для XML позволяют перемещаться по элементам XML-документа, согласно указаниям фокусируясь на отдельных аспектах документа. Класс XPathNavigator в.NET Framework это пример курсорного API в XML.

Пример использования класса XPathNavigator Пример использования класса XPathNavigator ( us/cpref/html/frlrfSystemXmlXPathXP...) в.NET Framework для получения имени исполнителя и названия первого compact-disc в элементе items. using System; using System.Xml; using System.Xml.XPath; public class Test { public static void Main(string[] args) { XmlDocument doc = new XmlDocument(); doc.Load("test.xml"); XPathNavigator nav = doc.CreateNavigator(); nav.MoveToFirstChild(); //переходит от корневого элемента к элементу документа (items) nav.MoveToFirstChild(); // переходит от элемента items к первому элементу compact-disc // переходит от элемента compact-disc к элементу artist nav.MoveToFirstChild(); nav.MoveToNext(); string artist = nav.Value; // переходит от элемента artist к элементу title nav.MoveToNext(); string title = nav.Value; Console.WriteLine("Artist={0}, Title={1}", artist, title); }

Потоковые API Потоковые API для обработки XML позволяет обрабатывать XML-документ, сохраняя в памяти только содержимое обрабатываемого в данный момент узла. Такие API делают возможной обработку больших XML-файлов без использования слишком больших объемов памяти. Существует два основных класса потоковых API для обработки XML: передающие XML-анализаторы и принимающие XML-анализаторы. Передающие синтаксические анализаторы, такие как SAX, проходят по XML-потоку, а затем при встрече с XML-узлами «выталкивают» события в зарегистрированные обработчики событий (методы обратного вызова). Принимающие анализаторы, такие как класс XmlReader ( в.NET Framework, работают в XML-потоке как однонаправленные курсоры.

Пример использования класса XmlReader в.NET Framework Ниже представлен пример использования класса XmlReader в.NET Framework для получения имени исполнителя и названия первого compact-disc в элементе items. using System; using System.Xml; public class Test{ public static void Main(string[] args){ string artist = null, title = null; XmlTextReader reader = new XmlTextReader("test.xml"); //переходим от корневого узла к элементу document (items) reader.MoveToContent(); /* продолжаем считывание до тех пор, пока не найдем первый элемент */ while(reader.Read()) { if((reader.NodeType == XmlNodeType.Element) && reader.Name.Equals("artist")){ artist = reader.ReadElementString(); title = reader.ReadElementString(); break; } } Console.WriteLine("Artist={0}, Title={1}", artist, title); } }

Введение в HTML DOM The HTML DOM defines a standard for accessing and manipulating HTML documents. What is the DOM? The DOM is a W3C (World Wide Web Consortium) standard. The DOM defines a standard for accessing documents like HTML and XML: "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document." The DOM is separated into 3 different parts / levels: Core DOM - standard model for any structured document XML DOM - standard model for XML documents HTML DOM - standard model for HTML documents The DOM defines the objects and properties of all document elements, and the methods (interface) to access them. What is the XML DOM? The XML DOM defines the objects and properties of all XML elements, and the methods (interface) to access them. If you want to study the XML DOM, find the XML DOM tutorial on our Home page.Home page What is the HTML DOM? The HTML DOM is: A standard object model for HTML A standard programming interface for HTML Platform- and language-independent A W3C standard The HTML DOM defines the objects and properties of all HTML elements, and the methods(interface) to access them. In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

XML DOM The XML DOM defines a standard way for accessing and manipulating XML documents. The DOM presents an XML document as a tree-structure. Знание XML DOM является обязательным для любого специалиста, работающего XML.

Введение XML DOM The XML DOM defines a standard for accessing and manipulating XML. What is the DOM? – The DOM is a W3C (World Wide Web Consortium) standard. – The DOM defines a standard for accessing documents like XML and HTML: – "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document." The DOM is separated into 3 different parts / levels: – Core DOM - standard model for any structured document – XML DOM - standard model for XML documents – HTML DOM - standard model for HTML documents The DOM defines the objects and properties of all document elements, and the methods (interface) to access them.

XML DOM Nodes In the DOM, everything in an XML document is a node. According to the DOM, everything in an XML document is a node. The DOM says: – The entire document is a document node – Every XML element is an element node – The text in the XML elements are text nodes – Every attribute is an attribute node – Comments are comment nodes

DOM Example Look at the following XML file (books.xml):books.xml Everyday Italian Giada De Laurentiis Harry Potter J K. Rowling XQuery Kick Start James McGovern Per Bothner Kurt Cagle James Linn Vaidyanathan Nagarajan Learning XML Erik T. Ray

The root node in the XML above is named. All other nodes in the document are contained within. The root node holds four nodes. The first node holds four nodes:,,, and, which contains one text node each, "Everyday Italian", "Giada De Laurentiis", "2005", and "30.00". Text is Always Stored in Text Nodes – A common error in DOM processing is to expect an element node to contain text. – However, the text of an element node is stored in a text node. In this example: 2005, the element node, holds a text node with the value "2005". – "2005" is not the value of the element!

Дерево узлов XML DOM The XML DOM views an XML document as a node-tree. All the nodes in the tree have a relationship to each other. The XML DOM Node Tree The XML DOM views an XML document as a tree-structure. The tree structure is called a node-tree. All nodes can be accessed through the tree. Their contents can be modified or deleted, and new elements can be created. The node tree shows the set of nodes, and the connections between them. The tree starts at the root node and branches out to the text nodes at the lowest level of the tree:

Узлы Parents, Children и Siblings Узлы (nodes) в дереве узлов имеют иерархические взаимосвязи друг с другом. Термины родитель (parent), ребенок (child) и sibling are used to describe the relationships. Parent nodes have children. Children on the same level are called siblings (brothers or sisters). In a node tree, the top node is called the root Every node, except the root, has exactly one parent node A node can have any number of children A leaf is a node with no children Siblings are nodes with the same parent The following image illustrates a part of the node tree and the relationship between the nodes. Because the XML data is structured in a tree form, it can be traversed without knowing the exact structure of the tree and without knowing the type of data contained within.

First Child - Last Child Look at the following XML fragment: Everyday Italian Giada De Laurentiis In the XML above, the element is the first child of the element, and the element is the last child of the element. Furthermore, the element is the parent node of the,,, and elements.

XML DOM процессоры (парсеры) XML Parser – The XML DOM contains methods (functions) to traverse XML trees, access, insert, and delete nodes. – However, before an XML document can be accessed and manipulated, it must be loaded into an XML DOM object. – An XML parser reads XML, and converts it into an XML DOM object that can be accessed with JavaScript. Most browsers have a built-in XML parser to read and manipulate XML. The parser converts XML into a JavaScript accessible object (the XML DOM).

Load an XML Document The following JavaScript fragment loads an XML document ("books.xml"):books.xml Example if (window.XMLHttpRequest) { xhttp=new XMLHttpRequest(); } else // IE 5/6 { xhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET","books.xml", false); xhttp.send(); xmlDoc=xhttp.responseXML; Code explained: – Create an XMLHTTP object – Open the XMLHTTP object – Send an XML HTTP request to the server – Set the response as an XML DOM object

Load an XML String The following code loads and parses an XML string: Example if (window.DOMParser) { parser=new DOMParser(); xmlDoc=parser.parseFromString(text,"text/xml"); } else // Internet Explorer { xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async="false"; xmlDoc.loadXML(text); } Note: Internet Explorer uses the loadXML() method to parse an XML string, while other browsers use the DOMParser object. Access Across Domains – For security reasons, modern browsers do not allow access across domains. – This means, that both the web page and the XML file it tries to load, must be located on the same server. – The examples on W3Schools all open XML files located on the W3Schools domain. – If you want to use the example above on one of your web pages, the XML files you load must be located on your own server.

XML DOM Load Functions The code for loading XML documents can be stored in a function. To make the code from the previous page simpler to maintain (and check for older browsers), it should be written as a function: function loadXMLDoc(dname) { if (window.XMLHttpRequest) { xhttp=new XMLHttpRequest(); } else { xhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",dname,false); xhttp.send(); return xhttp.responseXML; } The function above can be stored in the section of an HTML page, and called from a script in the page. The function described above, is used in all XML document examples in this tutorial!

An External JavaScript for loadXMLDoc() To make the code above even easier to maintain, and to make sure the same code is used in all pages, we store the function in an external file. The file is called "loadxmldoc.js", and will be loaded in the head section of an HTML page. Then, the loadXMLDoc() function can be called from a script in the page. The following example uses the loadXMLDoc() function to load books.xml:books.xml Example xmlDoc=loadXMLDoc("books.xml"); code goes here.....

The loadXMLString() Function To make the code from the previous page simpler to maintain (and check for older browsers), it should be written as a function: function loadXMLString(txt) { if (window.DOMParser) { parser=new DOMParser(); xmlDoc=parser.parseFromString(txt,"text/xml"); } else // Internet Explorer { xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async="false"; xmlDoc.loadXML(txt); } return xmlDoc; }The function above can be stored in the section of an HTML page, and called from a script in the page.

An External JavaScript for loadXMLString() We have stored the loadXMLString() function in a file called "loadxmlstring.js". Example text=" " text=text+" "; text=text+" Everyday Italian "; text=text+" Giada De Laurentiis "; text=text+" 2005 "; text=text+" "; text=text+" "; xmlDoc=loadXMLString(text); code goes here.....

XML DOM - Properties and Methods Properties and methods define the programming interface to the XML DOM. The DOM models XML as a set of node objects. The nodes can be accessed with JavaScript or other programming languages. In this tutorial we use JavaScript. The programming interface to the DOM is defined by a set standard properties and methods. Properties are often referred to as something that is (i.e. nodename is "book"). Methods are often referred to as something that is done (i.e. delete "book"). XML DOM Properties. These are some typical DOM properties (x is a node object): – x.nodeName - the name of x – x.nodeValue - the value of x – x.parentNode - the parent node of x – x.childNodes - the child nodes of x – x.attributes - the attributes nodes of x XML DOM Methods (x is a node object): – x.getElementsByTagName(name) - get all elements with a specified tag name – x.appendChild(node) - insert a child node to x – x.removeChild(node) - remove a child node from x

Example The JavaScript code to get the text from the first element in books.xml: txt = xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue After the execution of the statement, txt will hold the value "Everyday Italian" Explained: – xmlDoc - the XML DOM object created by the parser. – getElementsByTagName("title")[0] - the first element – childNodes[0] - the first child of the element (the text node) – nodeValue - the value of the node (the text itself)

XML DOM - Accessing Nodes examples below use the XML file books.xml. A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.books.xmlloadXMLDoc() Access a node using its index number in a node list This example uses the getElementsByTagname() method to get the third element in "books.xml" Access a node using its index number in a node list Loop through nodes using the length property This example uses the length property to loop through all elements in "books.xml" Loop through nodes using the length property See the node type of an element This example uses the nodeType property to get node type of the root element in "books.xml". See the node type of an element Loop through element nodes This example uses the nodeType property to only process element nodes in "books.xml". Loop through element nodes Loop through element nodes using node realtionships This example uses the nodeType property and the nextSibling property to process element nodes in "books.xml". Loop through element nodes using node realtionships Accessing Nodes You can access a node in three ways: – 1. By using the getElementsByTagName() method – 2. By looping through (traversing) the nodes tree. – 3. By navigating the node tree, using the node relationships.