XML xml version1 0 library name NET Developers
XML – пример <? xml version="1. 0"? > <library name=". NET Developer's Library"> <book> <title>Programming Microsoft. NET</title> <author>Jeff Prosise</author> <isbn>0 -7356 -1376 -1</isbn> </book> <title>Microsoft. NET for Programmers</title> <author>Fergal Grimes</author> <isbn>1 -930110 -19 -7</isbn> </book> </library>
XML – пример <? xml version="1. 0"? > заглавна част (пролог) атрибут <library name=". NET Developer's Library"> <book> <title>Programming Microsoft. NET</title> отварящ <author>Jeff Prosise</author> таг <isbn>0 -7356 -1376 -1</isbn> </book> <book> елемент <title>Microsoft. NET for Programmers</title> затварящ <author>Fergal Grimes</author> таг <isbn>1 -930110 -19 -7</isbn> </book> </library> стойност на елемент
Пространства от имена u Пространствата от имена (namespaces) в XML документите позволяват дефиниране и използване на тагове с еднакви имена: <? xml version="1. 0" encoding="UTF-8"? > <country: towns xmlns: country="urn: nakov-com: country" xmlns: town="http: //www. nakov. com/town"> <town: town> <town: name>Sofia</town: name> <town: population>1 200 000</town: population> <country: name>Bulgaria</country: name> </town: town> <town: name>Plovdiv</town: name> <town: population>700 000</town: population> <country: name>Bulgaria</country: name> </town: town> </country: towns>
Пространства от имена <? xml version="1. 0" encoding="UTF-8"? > <country: towns xmlns: country="urn: nakov-com: country" xmlns: town="http: //www. nakov. com/town"> <town: town> пространство с префикс "country" и <town: name>Sofia</town: name> URI идентификатор "urn: nakov<town: population>1 200 com: country 000</town: population> " <country: name>Bulgaria</country: name> </town: town> таг с име "name" от пространството "country", т. е. пълното име на тага е <town: town> "urn: nakov-com: country: name" <town: name>Plovdiv</town: name> <town: population>700 000</town: population> <country: name>Bulgaria</country: name> </town: town> </country: towns>
Пространства от имена u Позволява се използването на пространства по подразбиране: <? xml version="1. 0" encoding="windows-1251"? > <order xmlns="http: //www. hranitelni-stoki. com/orders"> <item> <name>бира "Загорка"</name> <ammount>8</ammount> пространство по <measure>бутилка</measure> подразбиране <price>3. 76</price> </item> <name>кебапчета</name> <ammount>12</ammount> <measure>брой</measure> пълното име на тага "item" е <price>4. 20</price> "http: //www. hranitelnik-stoki. com: item" </item> </order>
XSD схеми u XSD (XML Scheme Definition Language) е: v v мощен XML-базиран език за описание структурата на XML документи съдържа съвкупност от правила за таговете в документа и техните атрибути <? xml version="1. 0" encoding="UTF-8"? > <xs: schema xmlns: xs="http: //www. w 3. org/2001/XMLSchema"> <xs: element name="library"> <xs: complex. Type> <xs: sequence> <xs: element ref="book" max. Occurs="unbounded"/> </xs: sequence> <xs: attribute name="name" type="xs: string" use="optional"/> </xs: complex. Type> </xs: element> (примерът продължава)
XSD схеми <xs: element name="book"> <xs: complex. Type> <xs: sequence> <xs: element ref="title"/> <xs: element ref="author"/> <xs: element ref="isbn"/> </xs: sequence> </xs: complex. Type> </xs: element> <xs: element name="title" type="xs: string"/> name="author" type="xs: string"/> name="isbn" type="xs: string"/> </xs: schema> u u XSD схемите имат по-голяма изразителна мощ от DTD XSD постепенно измества DTD
XDR схеми – пример <? xml version="1. 0" encoding="UTF-8"? > <Schema xmlns="urn: schemas-microsoft-com: xml-data" xmlns: dt="urn: schemas-microsoft-com: datatypes"> <Element. Type name="author" model="closed" content="text. Only" dt: type="string"/> <Element. Type name="title" model="closed" content="text. Only" dt: type="string"/> <Element. Type name="isbn" model="closed" content="text. Only" dt: type="string"/> <Element. Type name="book" model="closed" content="elt. Only" order="seq"> <element type="title" min. Occurs="1" max. Occurs="1"/> <element type="author" min. Occurs="1" max. Occurs="1"/> <element type="isbn" min. Occurs="1" max. Occurs="1"/> </Element. Type> (примерът продължава)
XDR схеми – пример <Element. Type name="library" model="closed" content="elt. Only" order="seq"> <Attribute. Type name="name" dt: type="string" required="yes"/> <attribute type="name"/> <Attribute. Type name="xmlns" dt: type="string"/> <attribute type="xmlns"/> <element type="book" min. Occurs="1" max. Occurs="*"/> </Element. Type> </Schema>
Работа с DOM парсера u Даден е следния XML документ: <? xml version="1. 0"? > <library name=". NET Developer's Library"> <book> <title>Programming Microsoft. NET</title> <author>Jeff Prosise</author> <isbn>0 -7356 -1376 -1</isbn> </book> <title>Microsoft. NET for Programmers</title> <author>Fergal Grimes</author> <isbn>1 -930110 -19 -7</isbn> </book> </library>
DOM парсер – пример Xml. Document doc = new Xml. Document(); doc. Load("library. xml"); Xml. Node root. Node = doc. Document. Element; Console. Write. Line("Root node: {0}", root. Node. Name); foreach (Xml. Attribute atr in root. Node. Attributes) { Console. Write. Line("Attribute: {0}={1}", atr. Name, atr. Value); } foreach (Xml. Node node in root. Node. Child. Nodes) { Console. Write. Line("n. Book title = {0}", node["title"]. Inner. Text); Console. Write. Line("Book author = {0}", node["author"]. Inner. Text); Console. Write. Line("Book isbn = {0}", node["isbn"]. Inner. Text); }
Работа с DOM – пример u Удвояване на цените на бирата в следния XML документ <? xml version="1. 0" encoding="windows-1251"? > <items culture="en-US"> <item type="beer"> <name>Загорка</name> <price>0. 54</price> </item> <item type="food"> <name>кебапчета</name> <price>0. 48</price> </item> <item type="beer"> <name>Каменица</name> <price>0. 56</price> </items>
Работа с DOM – пример static void Main() { Xml. Document doc = new Xml. Document(). Load("items. xml"); string culture = doc. Document. Element. Attributes["culture"]. Value; Culture. Info number. Format = new Culture. Info(culture); foreach (Xml. Node node in doc. Document. Element) { if (node. Attributes["type"]. Value == "beer") { string current. Price. Str = node["price"]. Inner. Text; decimal current. Price = Decimal. Parse( current. Price. Str, number. Format); decimal new. Price = current. Price * 2; node["price"]. Inner. Text = new. Price. To. String(number. Format); } } } doc. Save("items. New. xml");
Xml. Reader – пример u Даден е XML документ, съдържащ списък от книги: <? xml version="1. 0"? > <library name=". NET Developer's Library"> <book> <title>Programming Microsoft. NET</title> <author>Jeff Prosise</author> <isbn>0 -7356 -1376 -1</isbn> </book> <title>Microsoft. NET for Programmers</title> <author>Fergal Grimes</author> <isbn>1 -930110 -19 -7</isbn> </book> </library>
Xml. Reader – пример u Извличане на всички заглавия: Xml. Text. Reader reader = new Xml. Text. Reader("library. xml"); while (reader. Read()) { if ((reader. Node. Type == Xml. Node. Type. Element) && (reader. Name == "title")) { Console. Write. Line(reader. Read. Element. String()); } } u Извличане на имената на всички елементи: Xml. Text. Reader reader = new Xml. Text. Reader("library. xml"); while (reader. Read()) { if (reader. Node. Type == Xml. Node. Type. Element) Console. Write. Line(reader. Name); }
Работа с Xml. Writer – пример public static void Main() { Xml. Text. Writer writer = new Xml. Text. Writer("lib. xml", Encoding. Get. Encoding("windows-1251")); writer. Formatting = Formatting. Indented; writer. Indent. Char = 't'; writer. Indentation = 1; try { writer. Write. Start. Document(); writer. Write. Start. Element("library"); writer. Write. Attribute. String("name", "My Library"); Write. Book(writer, "Code Complete", "Steve Mc. Connell", "155 -615 -484 -4"); Write. Book(writer, "Интернет програмиране с Java", "Светлин Наков", "954 -775 -305 -3"); Write. Book(writer, "Writing Solid Code", "Steve Maguire", "155 -615 -551 -4"); writer. Write. End. Document(); (примерът продължава)
Работа с Xml. Writer – пример } finally { writer. Close(); } } private static void Write. Book(Xml. Writer a. Writer, string a. Title, string a. Author, string a. Isbn) { a. Writer. Write. Start. Element("book"); a. Writer. Write. Element. String("title", a. Title); a. Writer. Write. Element. String("author", a. Author); a. Writer. Write. Element. String("isbn", a. Isbn); a. Writer. Write. End. Element(); }
Работа с Xml. Writer – пример u Резултатен XML документ: <? xml version="1. 0" encoding="windows-1251"? > <library name="My Library"> <book> <title>Code Complete</title> <author>Steve Mc. Connell</author> <isbn>155 -615 -484 -4</isbn> </book> <title>Интернет програмиране с Java</title> <author>Светлин Наков</author> <isbn>954 -775 -305 -3</isbn> </book> <title>Writing Solid Code</title> <author>Steve Maguire</author> <isbn>155 -615 -551 -4</isbn> </book> </library>
Валидация на XML – пример u Имаме следния XML файл: <? xml version="1. 0"? > <library xmlns="http: //www. nakov. com/schemas/library" xmlns: xsi="http: //www. w 3. org/2001/XMLSchema-instance" xsi: schema. Location="http: //www. nakov. com/schemas/library. xsd" name=". NET Developer's Library"> <book> <title>Programming Microsoft. NET</title> <author>Jeff Prosise</author> <isbn>0 -7356 -1376 -1</isbn> </book> <title>Microsoft. NET for Programmers</title> <author>Fergal Grimes</author> <isbn>1 -930110 -19 -7</isbn> </book> </library>
Валидация на XML – пример u В него е указана използваната XSD схема: <? xml version="1. 0"? > <library xmlns="http: //www. nakov. com/schemas/library" xmlns: xsi="http: //www. w 3. org/2001/XMLSchema-instance" xsi: schema. Location="http: //www. nakov. com/schemas/library. xsd" name=". NET Developer's Library"> <book> <title>Programming Microsoft. NET</title> <author>Jeff Prosise</author> URI на <isbn>0 -7356 -1376 -1</isbn> използваното </book> пространство URL<book> адрес (в Интернет), от имена където<title>Microsoft е публикувана. NET for Programmers</title> XSD схемата <author>Fergal Grimes</author> <isbn>1 -930110 -19 -7</isbn> </book> </library>
Валидация на XML – пример u XSD схемата, по която ще валидираме: <? xml version="1. 0" encoding="UTF-8"? > <xs: schema xmlns: xs="http: //www. w 3. org/2001/XMLSchema" xmlns="http: //www. nakov. com/schemas/library" target. Namespace="http: //www. nakov. com/schemas/library"> <xs: element name="library"> <xs: complex. Type> <xs: sequence> Указано е, че схемата описва <xs: element ref="book" елементите от пространството max. Occurs="unbounded"/> http: //www. nakov. com/schemas/library </xs: sequence> <xs: attribute name="name" type="xs: string" use="optional"/> </xs: complex. Type> </xs: element> (примерът продължава)
Валидация на XML – пример u XSD схемата, по която ще валидираме: <xs: element name="book"> <xs: complex. Type> <xs: sequence> <xs: element ref="title"/> <xs: element ref="author"/> <xs: element ref="isbn"/> </xs: sequence> </xs: complex. Type> </xs: element> <xs: element name="title" type="xs: string"/> <xs: element name="author" type="xs: string"/> <xs: element name="isbn" type="xs: string"/> </xs: schema>
Валидация на XML – пример u Кодът, който валидира XML документа: using System; using System. Xml. Schema; … static void Main() { Xml. Text. Reader tr = new Xml. Text. Reader("library. xml"); Xml. Validating. Reader vr = new Xml. Validating. Reader(tr); vr. Schemas. Add("http: //www. nakov. com/schemas/library", "library. xsd"); vr. Validation. Type = Validation. Type. Schema; vr. Validation. Event. Handler += new Validation. Event. Handler (Validation. Handler); m. Valid = true; (примерът продължава)
Валидация на XML – пример u Кодът, който валидира XML документа: while(vr. Read()) { } } // Do nothing, just read the whole document. if (m. Valid) { Console. Write. Line("The document is valid. "); } public static void Validation. Handler( object a. Sender, Validation. Event. Args a. Args) { m. Valid = false; Console. Write. Line("***Validation error"); Console. Write. Line("t. Severity: {0}", a. Args. Severity); Console. Write. Line("t. Message: {0}", a. Args. Message); }
XPath и Xml. Node – пример u Даден е следния XML документ: <? xml version="1. 0" encoding="windows-1251"? > <items> <item type="beer"> <name>Загорка</name> <price>0. 54</price> </item> <item type="food"> <name>кебапчета</name> <price>0. 48</price> </item> <item type="beer"> <name>Каменица</name> <price>0. 56</price> </items>
XPath и Xml. Node – пример u Търсим в него имената на всички стоки от тип “бира”: <? xml version="1. 0" encoding="windows-1251"? > <items> <item type="beer"> <name>Загорка</name> <price>0. 54</price> Можем да ползваме XPath израза </item> /items/item[@type='beer']/name <item type="food"> <name>кебапчета</name> <price>0. 48</price> </item> <item type="beer"> <name>Каменица</name> <price>0. 56</price> </items>
XPath и Xml. Node – пример u Можем да използваме следния код: using System; using System. Xml; class Test. XPath { static void Main(string[] args) { Xml. Document xml. Doc = new Xml. Document(); xml. Doc. Load("items. xml"); string query = "/items/item[@type='beer']/name"; Xml. Node. List beer. Names. List = xml. Doc. Select. Nodes(query); foreach (Xml. Node beer. Name in beer. Names. List) { Console. Write. Line(beer. Name. Inner. Text); } } }
XPath. Navigator – пример u Промоция – намаляване на цената на бирата с 20% using System; System. Xml. XPath; System. Globalization; class XPath. Navigator. Demo { public const decimal DISCOUNT = (decimal) 0. 20; static void Main() { Xml. Document xml. Doc = new Xml. Document(); xml. Doc. Load("items. xml"); Culture. Info number. Format = new Culture. Info("en-US"); (примерът продължава)
XPath. Navigator – пример XPath. Navigator nav = xml. Doc. Create. Navigator(); string x. Path. Query = "/items/item[@type='beer']/price"; XPath. Node. Iterator iter = nav. Select(x. Path. Query); while (iter. Move. Next()) { XPath. Navigator current. Node = iter. Current; Xml. Node xml. Node = ((IHas. Xml. Node) current. Node). Get. Node(); string price. Str = xml. Node. Inner. Text; decimal price = Decimal. Parse(price. Str, number. Format); price = price * (1 - DISCOUNT); xml. Node. Inner. Text = price. To. String(number. Format); } } } xml. Doc. Save("items. New. xml");
XPath. Document – пример using System; System. Xml. XPath; class XPath. Navigator. Demo { static void Main() { // Create fast forward-only XPath processor XPath. Document doc = new XPath. Document( ". . /xml-files/items. xml"); XPath. Navigator nav = doc. Create. Navigator(); XPath. Expression expr = nav. Compile( "/items/item[@type='beer']/name"); XPath. Node. Iterator iter = nav. Select(expr); } } while (iter. Move. Next()) { XPath. Navigator current. Node = iter. Current; Console. Write. Line(current. Node. Value); }
XSL трансформации <html> <body> <h 1>Моята библиотека</h 1> <table bgcolor="#E 0 E 0 E 0" cellspacing="1"> <tr bgcolor="#EEEEEE"> <td><b>Заглавие</b></td> <td><b>Автор</b></td> </tr> <xsl: for-each select="/library/book"> <tr bgcolor="white"> <td><xsl: value-of select="title"/></td> <td><xsl: value-of select="author"/></td> </tr> </xsl: for-each> </table> </body> </html> </xsl: template> </xsl: stylesheet>
XSL трансформации – пример u Преобразуване на XML документ по даден XSL шаблон: using System; using System. Xml. Xsl; class XSLTransform. Demo { static void Main() { Xsl. Transform xslt = new Xsl. Transform(); xslt. Load("library-xml 2 html. xsl"); xslt. Transform("library. xml", "library. html", null); } }
Използвана литература u u u MSDN Library – http: //msdn. microsoft. com Стоян Йорданов, Работа с XML – http: //www. nakov. com/dotnet/2003/lectures/Working-with-XML. doc MSDN Training, Introduction to XML and the Microsoft®. NET Platform (MOC 2500 A)
- Slides: 87