1 / 33

C# and XML

C# and XML. by Edward Bronejko. Part II Using the Way Cool System.XML namespace. Part I Summary of XML. Part I. Learn XML in 2 Minutes or less Fasten your seatbelts!. What is XML?. e X tensible M arkup L anguage Data is marked up with XML tags similar to HTML tags in Web pages.

talasi
Download Presentation

C# and XML

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C# and XML by Edward Bronejko Part II Using the Way Cool System.XML namespace Part I Summary of XML

  2. Part I Learn XML in 2 Minutes or less Fasten your seatbelts!

  3. What is XML? • eXtensible Markup Language • Data is marked up with XML tags similar to HTML tags in Web pages. • XML is a Meta Language – It is used to create other languages (XSL, XHTML, etc.)

  4. HTML Tags: <html> <head> <title>Page Title</title> </head> <body bgcolor=“red”> This is a Web page… </body> </html>

  5. XML Tags <?xml version=“1.0” ?> <course title=“C Sharp” instructor=“Glen Harding” semester=“Spring 2004”> <lecture date=“2004-01-21”> <topic>Introduction</topic> <reading>Chapter 1</reading> <lab /> </lecture> <lecture date=“2004-01-28”> <topic>A Simple Welcome Program</topic> <reading>Chapter 2</reading> <lab>Demo of a for loop, while loop, foreach loop</lab> </lecture> </course>

  6. Attribute Value Attribute Name Element XML Attributes & Elements • A set of opening and closing tags plus the data content in between are called an Element. <topic>Introduction</topic> • Data stored within an opening tag is called an attribute. <lecture date=“2004-01-21” >

  7. Well Formed XML Documents • All element and attribute names must follow proper naming conventions. • Elements must be properly nested. • Start tags must have ending tags unless they take the form of the empty element. • There can be only one root element which contains all others.

  8. XML Validation • When being Well Formed isn’t enough! • Validation allows you to specify rules about the structure of the document. • The number of times an element can appear. • The order in which elements must appear. • Which attributes are mandatory (if any). • How an attribute is specified.

  9. Validating XML Documents • The XML document can be validated in either of two ways • Using a DTD – Document Type Definition • Using XSD (the XML Schema Language) • XSD stands for XML Schema Definition

  10. DTD & XSD Schema • DTD – Document Type Definitions: • Established Technology • More XML Parsers validate with DTD • XML Schema (XSD): • Newer Technology • Written in XML • More powerful than DTD

  11. XML Schema Example <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="course"> <xs:complexType> <xs:element name="lecture" minOccur="0" maxOccur="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="topic" type="xs:string" /> <xs:element name="reading" type="xs:string" nillable="true" /> <xs:element name="lab" type="xs:string" nillable="true" /> </xs:sequence> <xs:attribute name="date" type="date" /> </xs:complexType> </xs:element> <xs:attribute name="title" type="xs:string" /> <xs:attribute name="instructor" type="xs:string" /> <xs:attribute name="semester" type="xs:string" /> </xs:complexType> </xs:element> </xs:schema>

  12. XSL • Extensible Stylesheet Language • Used to transform an XML document for output • Similar to Cascading Style Sheets for HTML but much more powerful • Can produce other XML, HTML, or PDF documents (and much more)

  13. XPath • XPath is used to query an XML document to retrieve specific information • Similar to how SQL queries a database

  14. XML Family Summary • XML: Database document • XSD: Validates XML document • XSL: Transforms or displays XML document • XPath: Queries the XML document

  15. Part II Learn to use C# with XML in 3 minutes or less Tighten your seatbelt even more!

  16. C# and XML The System.Xml Namespace includes: • System.Xml.Schema • System.Xml.Xsl • System.Xml.XPath • and a whole lot more!

  17. System.Xml.Schema Includes: • ValidationEventArgs • XmlSchemaCollection • XmlSchemaDatatype • XmlSchemaElement

  18. System.Xml.Xsl Includes: • XsltArgumentList • XsltCompileException • XstlContext • XsltException • XsltTransform

  19. System.Xml.XPath Includes: • XPath.Document • XPath.Exception • XPath.Expression • XPath.Navigator • XPath.NodeIterator

  20. Using System.Xml.XPath • First Create Sample.xml – A sample XML document. • Next Create Sample.cs – A C# program using System.Xml.XPath to query information from sample.xml.

  21. Create Sample.xml <?xml version="1.0" encoding="utf-8" ?> <Catalog xmlns:test="uri:test"> <Company name="Bankrupcy International"> <ProductFamily LastUpdate="2001-08-26"> <Product ProductID="CFC3" items="34"> <test:color>green</test:color> <size>M</size> <price>31.99</price> <color>green</color> <size>L</size> <price>45.99</price> </Product> <Product ProductID="CFC4"> <color>black</color> <size>L</size> <price>32.99</price> </Product> </ProductFamily> </Company> </Catalog>

  22. Create Sample.cs using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Xml.XPath; namespace XPathExamples { public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Button button1; private System.Windows.Forms.ListBox listBox1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button2; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Label label2; private System.ComponentModel.Container components = null;

  23. public Form1() { InitializeComponent(); } protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.listBox1 = new System.Windows.Forms.ListBox(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.button2 = new System.Windows.Forms.Button(); this.textBox2 = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.SuspendLayout();

  24. // button1 this.button1.Location = new System.Drawing.Point(135, 128); this.button1.Name = "button1"; this.button1.TabIndex = 5; this.button1.Text = "Execute"; this.button1.Click += new System.EventHandler(this.button1_Click); // listBox1 this.listBox1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.listBox1.Location = new System.Drawing.Point(44, 168); this.listBox1.Name = "listBox1"; this.listBox1.Size = new System.Drawing.Size(256, 160); this.listBox1.TabIndex = 6;

  25. // textBox1 this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.textBox1.Location = new System.Drawing.Point(44, 96); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(256, 20); this.textBox1.TabIndex = 4; this.textBox1.Text = "Company"; // label1 this.label1.Location = new System.Drawing.Point(8, 72); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(128, 23); this.label1.TabIndex = 3; this.label1.Text = "Choose an XPath Query";

  26. // button2 this.button2.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.button2.Location = new System.Drawing.Point(135, 344); this.button2.Name = "button2"; this.button2.TabIndex = 7; this.button2.Text = "End"; this.button2.Click += new System.EventHandler(this.button2_Click); // textBox2 this.textBox2.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.textBox2.Location = new System.Drawing.Point(44, 32); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(256, 20); this.textBox2.TabIndex = 2; this.textBox2.Text = "Catalog";

  27. // label2 this.label2.Location = new System.Drawing.Point(8, 8); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(128, 23); this.label2.TabIndex = 1; this.label2.Text = "Set Context"; // Form1 this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(344, 381); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.label2, this.textBox2, this.button2, this.label1, this.textBox1, this.listBox1, this.button1}); this.Name = "Form1"; this.Text = "XPathSample"; this.ResumeLayout(false); } #endregion

  28. static void Main() { Application.Run(new Form1()); } private void button1_Click(object sender, System.EventArgs e) { try { string strXPathQuery = textBox1.Text; string strXPathContext = textBox2.Text; XPathDocument objXPath = new XPathDocument(Application.StartupPath + "\\sample.xml"); XPathNavigator objXPathNav = objXPath.CreateNavigator(); //Set the Context of the query XPathNodeIterator objXPathIter = objXPathNav.Select(strXPathContext); while (objXPathIter.MoveNext()) {} //Execute the query XPathNodeIterator objXPathIter2 = objXPathIter.Current.Select(strXPathQuery);

  29. listBox1.Items.Clear(); listBox1.Items.Add("Calculating..."); MessageBox.Show("Click OK to display results."); listBox1.Items.Clear(); while (objXPathIter2.MoveNext()) { listBox1.Items.Add(objXPathIter2.Current.Name + ":" + objXPathIter2.Current.Value); } } catch (Exception ex) { MessageBox.Show("The following error occurred : " + ex.Message); } } private void button2_Click(object sender, System.EventArgs e) { Application.Exit(); } } }

  30. Running Sample.cs Setting Context to Catalogand XPath Query to Company returns all text nodes descended from Company <?xml version="1.0" encoding="utf-8" ?> <Catalog xmlns:test="uri:test"> <Company name="Bankrupcy International"> <ProductFamily LastUpdate="2001-08-26"> <Product ProductID="CFC3" items="34"> <test:colour>green</test:colour> <size>M</size> <price>31.99</price> <color>green</color> <size>L</size> <price>45.99</price> </Product> <Product ProductID="CFC4"> <color>black</color> <size>L</size> <price>32.99</price> </Product> </ProductFamily> </Company> </Catalog>

  31. Run Sample.cs Again Setting Context to //Product[1]and XPath Query to @* returns all attribute nodes of the first Product tag (the * is a wildcard). <?xml version="1.0" encoding="utf-8" ?> <Catalog xmlns:test="uri:test"> <Company name="Bankrupcy International"> <ProductFamily LastUpdate="2001-08-26"> <Product ProductID="CFC3" items="34"> <test:colour>green</test:colour> <size>M</size> <price>31.99</price> <color>green</color> <size>L</size> <price>45.99</price> </Product> <Product ProductID="CFC4"> <color>black</color> <size>L</size> <price>32.99</price> </Product> </ProductFamily> </Company> </Catalog>

  32. Sample.cs XPath Code Details private void button1_Click(object sender, System.EventArgs e) { try { string strXPathQuery = textBox1.Text; string strXPathContext = textBox2.Text; XPathDocument objXPath = new XPathDocument(Application.StartupPath + "\\sample.xml"); XPathNavigator objXPathNav = objXPath.CreateNavigator(); //Set the Context of the query XPathNodeIterator objXPathIter = objXPathNav.Select(strXPathContext); while (objXPathIter.MoveNext()) {} //Execute the query XPathNodeIterator objXPathIter2 = objXPathIter.Current.Select(strXPathQuery);

  33. Bibliography • Colathoor, xml processing in C#,http://devresource.hp.com/drc/technical_articles/xmlprocess/index.jsp, Hewlett-Packard Development Company, L.P. 2003 • Deitel, Listfield, et al., C# How to Program, Prentice Hall, NJ, 2002 • Fraser & Livingstone, Beginning C# XML, Wrox, Birmingham, UK, 2002 • Gulbransen, et al., Special Edition, Using XML, 2nd ed., Que, Indianapolis, IN, 2002

More Related