330 likes | 472 Views
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.
E N D
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? • 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.)
HTML Tags: <html> <head> <title>Page Title</title> </head> <body bgcolor=“red”> This is a Web page… </body> </html>
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>
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” >
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.
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.
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
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
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>
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)
XPath • XPath is used to query an XML document to retrieve specific information • Similar to how SQL queries a database
XML Family Summary • XML: Database document • XSD: Validates XML document • XSL: Transforms or displays XML document • XPath: Queries the XML document
Part II Learn to use C# with XML in 3 minutes or less Tighten your seatbelt even more!
C# and XML The System.Xml Namespace includes: • System.Xml.Schema • System.Xml.Xsl • System.Xml.XPath • and a whole lot more!
System.Xml.Schema Includes: • ValidationEventArgs • XmlSchemaCollection • XmlSchemaDatatype • XmlSchemaElement
System.Xml.Xsl Includes: • XsltArgumentList • XsltCompileException • XstlContext • XsltException • XsltTransform
System.Xml.XPath Includes: • XPath.Document • XPath.Exception • XPath.Expression • XPath.Navigator • XPath.NodeIterator
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.
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>
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;
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();
// 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;
// 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";
// 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";
// 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
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);
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(); } } }
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>
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>
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);
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