60
Object Innovations Course 441 E. J. Jones Robert J. Oberg William W. Provost Student Guide Revision 2.1 XML Parsing Using C# and .NET

XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

  • Upload
    others

  • View
    30

  • Download
    0

Embed Size (px)

Citation preview

Page 1: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

Object Innovations Course 441

E. J. Jones Robert J. Oberg

William W. Provost

Student Guide Revision 2.1

XML Parsing Using C# and .NET

Page 2: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

Rev. 2.1 Copyright © 2006 Object Innovations ii All Rights Reserved

XML Parsing Using C# and .NET Rev. 2.1 This course consists of the first two days of the four-day Object Innovations course: 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Object Innovations. Product and company names mentioned herein are the trademarks or registered trademarks of their respective owners. Copyright © 2006 Object Innovations. All rights reserved. Object Innovations 877-558-7246 www.objectinnovations.com Printed in the United States of America.

Page 3: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

Rev. 2.1 Copyright © 2006 Object Innovations iii All Rights Reserved

Table of Contents (Overview) Chapter 1 .NET Framework XML Overview Chapter 2 Reading XML Streams in .NET Chapter 3 Validating XML Streams Chapter 4 Writing XML Streams in .NET Chapter 5 The Document Object Model in .NET Chapter 6 Manipulating XML Information with the DOM Appendix A Zenith Courseware Case Study Appendix B Learning Resources

Page 4: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

Rev. 2.1 Copyright © 2006 Object Innovations iv All Rights Reserved

Prerequisites and Pacing

• C# programming experience is required for this course.

• Some experience with XML is also assumed.

− The student should understand basic XML grammar, and be able to read and write well-formed XML documents.

− The concept of a valid XML document, as opposed to a merely well-formed one, should be understood, via some experience with either DTDs or XML Schema.

• This course contains a great deal of material.

− Please give feedback to the instructor at the beginning of the course on the topics of most interest to you, and during the course about how the pacing is working for you.

Page 5: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

Rev. 2.1 Copyright © 2006 Object Innovations v All Rights Reserved

Labs

• The course relies on hands-on experience in various topics and techniques.

• Application code for this course is all in XmlCs under the top-level directory, which by default is c:\OIC.

• Where possible, starter code is provided to take work off your hands that would be largely irrelevant to the topic of the lab; thus you can be as productive as possible in the time allotted and focus on the topic at hand.

• The labs are installed by running the simple self-extractor:

Install_XmlCs_21.exe

− This can be found in the file 441_Lab_21.zip, which is available on Object Innovations’ lab download page:

http://www.objectinnovations.com/Labs/index.html

Page 6: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

Rev. 2.1 Copyright © 2006 Object Innovations vi All Rights Reserved

Directory Structure for the Course

• The course has a combination of directories under the course root directory c:\OIC\XmlCs.

− Under this root, the chapter directories Chap01, Chap02, and so on, hold code examples, including all the starting, intermediate and answer versions of all the labs.

− The Labs directory holds one subdirectory for each lab in the course, named for the lab number.

− The Demos directory is provided for performing in-class demonstrations led by the instructor.

− The Tools directory contains the executables of XML tools that are provided with the course.

− The CaseStudy directory contains files pertaining to the Zenith Courseware case study.

Page 7: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

Rev. 2.1 Copyright © 2006 Object Innovations vii All Rights Reserved

Table of Contents (Detailed)

Chapter 1 .NET Framework XML Overview .............................................................. 1 XML................................................................................................................................ 3 Parsing XML................................................................................................................... 4 Using XML in .NET Applications.................................................................................. 5 The .NET XML Classes.................................................................................................. 7 Parsing Techniques ......................................................................................................... 9 .NET Parsing Techniques ............................................................................................. 10 Parsing Example ........................................................................................................... 11 How Does SAX and MSXML Fit Into .NET?.............................................................. 12 XmlReader and XmlWriter Features ............................................................................ 13 XmlTextWriter Demo................................................................................................... 15 .NET DOM Parser Features.......................................................................................... 17 XmlDocument Demo.................................................................................................... 18 Demo – Testing Parser Features ................................................................................... 19 Other XML Features in .NET ....................................................................................... 23 XML and the Web ........................................................................................................ 24 Internet Explorer and XML .......................................................................................... 25 Summary ....................................................................................................................... 26

Chapter 2 Reading XML Streams in .NET ................................................................ 27 The .NET XmlReader Classes ...................................................................................... 29 The XmlReader Properties............................................................................................ 30 Accessing Nodes........................................................................................................... 31 Reading Attributes ........................................................................................................ 32 MoveToNextAttribute................................................................................................... 33 XmlTextReader Example.............................................................................................. 34 Using Streams with XmlTextReader ............................................................................ 35 The XmlTextReader Demo........................................................................................... 36 Catching the Exceptions ............................................................................................... 40 Lab 2A .......................................................................................................................... 42 Moving Around the Document ..................................................................................... 43 MoveReader Example................................................................................................... 44 Handling Whitespace .................................................................................................... 45 Parsing a Specific Document ........................................................................................ 46 Parsing the Top-Level Elements................................................................................... 47 Subroutines ................................................................................................................... 48 Looping for Children .................................................................................................... 49 Text via Brute Force ..................................................................................................... 50 ReadElementString()..................................................................................................... 51 Zenith Courseware Case Study..................................................................................... 52 Lab 2B........................................................................................................................... 53 Miscellaneous Reading Methods .................................................................................. 54 Handling Namespaces................................................................................................... 55

Page 8: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

Rev. 2.1 Copyright © 2006 Object Innovations viii All Rights Reserved

The XmlNodeReader Class........................................................................................... 57 Creating XmlReaders in .NET 2.0................................................................................ 59 Benefits of Using XmlReader.Create()......................................................................... 60 Summary ....................................................................................................................... 61

Chapter 3 Validating XML Streams........................................................................... 69 Valid XML.................................................................................................................... 71 The Trouble with Well-Formed XML .......................................................................... 72 Formal Type Information.............................................................................................. 73 DTDs and XML Schema .............................................................................................. 74 Example – DTD for a Stereo System............................................................................ 75 XML Schema for a Stereo System................................................................................ 76 DTD and XML Schema Comparison ........................................................................... 77 Invalid XML ................................................................................................................. 78 A Validation Tool ......................................................................................................... 79 Example – Validating Stereo Systems.......................................................................... 80 Creating Schema with Visual Studio ............................................................................ 83 Using the Schema Graphical Editor.............................................................................. 87 Lab 3A .......................................................................................................................... 88 Validating XML Streams.............................................................................................. 89 Validation Settings........................................................................................................ 90 Validation Flags ............................................................................................................ 91 .NET Validation Code .................................................................................................. 93 Validation Events.......................................................................................................... 95 Lab 3B........................................................................................................................... 96 Summary ....................................................................................................................... 97

Chapter 4 Writing XML Streams in .NET............................................................... 103 Writing XML in .NET ................................................................................................ 105 The XmlWriter Class .................................................................................................. 106 WriteMovie Example.................................................................................................. 108 The XmlTextWriter Class........................................................................................... 109 The State of Writer...................................................................................................... 110 Creating XmlWriters in .NET 2.0............................................................................... 111 Lab 4A ........................................................................................................................ 112 Writing Out Elements ................................................................................................. 113 Writing Nested Elements ............................................................................................ 115 Writing Attributes ....................................................................................................... 116 Lab 4B......................................................................................................................... 118 Summary ..................................................................................................................... 119

Chapter 5 The Document Object Model in .NET .................................................... 127 The Document Object Model (DOM)......................................................................... 129 Origins of the DOM.................................................................................................... 130 DOM2 Structure.......................................................................................................... 131 DOM Tree Model ....................................................................................................... 132 Tree Model Example................................................................................................... 133 .NET DOM Classes .................................................................................................... 134

Page 9: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

Rev. 2.1 Copyright © 2006 Object Innovations ix All Rights Reserved

The XmlDocument Class............................................................................................ 135 The XmlNode Class – Basic Parsing.......................................................................... 137 Polymorphic Node Types ........................................................................................... 138 The XmlNode Class – Node Types ............................................................................ 139 Example – Walking the Child List.............................................................................. 140 Example – A Recursive Tree Walk ............................................................................ 141 Basic Parsing............................................................................................................... 143 Basic Parsing Example ............................................................................................... 144 Lab 5A ........................................................................................................................ 146 The XmlElement Class ............................................................................................... 147 The XmlAttribute Class .............................................................................................. 148 The XmlAttributeCollection Class ............................................................................. 149 The XmlText Class ..................................................................................................... 150 Lab 5B......................................................................................................................... 151 The XmlNodeList Class.............................................................................................. 152 Using a foreach Loop.................................................................................................. 153 Another Attribute Example......................................................................................... 154 Validation.................................................................................................................... 155 Lab 5C......................................................................................................................... 156 Summary ..................................................................................................................... 157

Chapter 6 Manipulating XML Information with the DOM ................................... 167 Modifying Documents ................................................................................................ 169 Build A DOM Tree – Demo ....................................................................................... 170 The XmlNode Class – Modifications ......................................................................... 174 Legal and Illegal Modifications .................................................................................. 175 Managing Children ..................................................................................................... 176 Cloning........................................................................................................................ 177 Modifying Elements.................................................................................................... 178 Splitting Text and Normalizing .................................................................................. 179 Modifying Attributes .................................................................................................. 180 Lab 6 ........................................................................................................................... 181 Summary ..................................................................................................................... 182

Appendix A Zenith Courseware Case Study............................................................ 189

Appendix B Learning Resources ............................................................................... 203

Page 10: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

Rev. 2.1 Copyright © 2006 Object Innovations x All Rights Reserved

Page 11: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 1 All Rights Reserved

Chapter 1

.NET Framework XML Overview

Page 12: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 2 All Rights Reserved

.NET Framework XML Overview

Objectives

After completing this unit you will be able to:

• Describe the role of parsing in XML applications.

• Identify the three main parsing APIs in .NET, and describe the major differences between them.

• Describe the major .NET Framework XML classes.

• Describe XML serialization and its role throughout the Framework.

• Discuss the close relationship between XML and ADO.NET.

• Describe XPath and XSLT and the .NET Framework support for these XML technologies.

Page 13: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 3 All Rights Reserved

XML

• The eXtensible Markup Language, or XML, has become a very popular choice for a wide array of software applications:

− Traditional web applications enhanced with XML as an HTML transformation source

− XML as a portable format for data exchange and archiving

− Business-to-business messaging and Web Services

− Many more

• It is surprising when learning the language how much can be accomplished using XML and related standards and generic, pre-built tools, without any traditional application code.

− XML Stylesheet Language for Transformations, or XSLT, enables moderately sophisticated document transformation.

− Modern web browsers can present XML documents to users with the aid of XSLT, XSL, or Cascading Style Sheets (CSS), even including hyperlinks with the help of XLink.

− Detailed document structure and content validation can be effected using XML Schema and a validating parser.

Page 14: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 4 All Rights Reserved

Parsing XML

• At some point, however, the information in XML documents must be available to application code.

• At its most basic, the process by which an application reads the information in an XML document is known as parsing the document.

− Clearly, the literal meaning of the term refers to the gritty work of reading the document as a stream of characters, and interpreting that stream according to XML grammar.

− Stated another way, the parsing task might be seen as that of abstracting the document content – often called its information set or infoset – from its lexical representation in XML proper.

− This information set can then be read by application code, using any number of possible models.

− Document validation can also be performed as part of parsing.

• All these jobs are quite complex, but, thanks to the design of XML, also generic.

• Thus individual business applications do not have to write their own parsing code, instead leveraging prebuilt packages that offer APIs to their parsing capabilities.

Page 15: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 5 All Rights Reserved

Using XML in .NET Applications

• Microsoft is a big proponent of XML and is a huge participant in the W3C.

• The .NET Framework has many areas which are enabled for XML processing.

− Database queries can be returned in an XML format with XML Schema definitions.

− Many configuration files in .NET projects are stored in XML format.

− Web Services uses the XML based SOAP protocol to remotely call objects on a server.

− The Universal Description, Discovery, and Integration (UDDI) service uses XML to request and return data to clients.

• XML support is built into the .NET Framework

• The many different types of .NET applications utilize services provided in the Framework.

− The XML services we are going to look at includes .NET classes that interact with the CLR.

Page 16: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 6 All Rights Reserved

The Core .NET XML Namespaces

• The System.Xml namespace and its subsidiary namespaces encapsulate the XML functionality in the .NET Framework.

− They contain the classes that parse, validate, traverse, and create XML streams.

− The namespace classes support the following W3C XML standards.

XML 1.0 and XML namespaces XML schemas XPath XSLT DOM level 1& 2 core SOAP 1.2 (object serialization)

• The System.Xml namespace contains the essential and

major classes for reading and writing.

• The System.Xml namespace contains four subsidiary namespaces.

− System.Xml.Schema – this namespace contains the XML classes that provide support for XML Schemas definition language (XSD) schemas.

− System.Xml.Serialization - classes that are used to serialize objects into XML streams. The primary class is XMLSerializer.

− System.Xml.XPath - contains the XPath parser and evaluation engine for querying XML data streams.

− System.Xml.Xsl – these classes support the Extensible Stylesheet Transformation (XSLT).

Page 17: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 7 All Rights Reserved

The .NET XML Classes

• The parent class for the nodes found in an XML data stream is called XmlNode.

• Depending upon the specific type of node the XmlNode class has six derived classes. They are:

− System.Xml.XmlLinkedNode

− System.Xml.XmlAttribute

− System.Xml.XmlDocument

− System.Xml.XmlDocumentFragment

− System.Xml.XmlEntity

− System.Xml.XmlNotation

• Each of the derived classes contains the properties and methods that are suitable for that type of node.

Page 18: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 8 All Rights Reserved

.NET XML Classes and Interfaces

• In addition to specifying class hierarchy, the classes have three interfaces in common:

− ICloneable – Xml nodes can be copied to create a new instance.

− IEnumerable – Xml nodes support the foreach loop for C#.

− IXPathNavigable – gives the ability to retrieve data from the node using XPath queries.

− We will use all of these when we start coding.

• Parsers in the System.Xml namespace are found in several classes.

− XmlTextReader — this class is a fast non-validating forward-only parser.

− XmlValidatingReader — this parser validates on XML input using DTDs, Microsoft’s XML-Data Reduced (XDR) schema, and W3C’s XML Schema definition language (XSD) schema validation.

− XmlTextWriter — this class provides the methods to assist you in writing syntactically correct XML. It can write to a file, stream, console, and other output devices.

− XmlDocument — this class implements the W3C Core Document Object Model Level 1 and Level 2. It stores the XML tree in memory and allows you traverse and modify the nodes.

Page 19: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 9 All Rights Reserved

Parsing Techniques

• There are two traditional methods for parsing XML streams, and each has advantages and disadvantages.

• The Document Object Model

− The DOM is a W3C standard caching parser and is widely adopted in many programming environments.

− Good if you need to move forward and backward in the stream and if you need to modify the node values.

− Bad choice if you’re forward scanning only and not modifying the document.

− The DOM keeps the entire parsed tree in-memory thereby consuming computer resources.

• The Simple API for XML (SAX)

− This forward-only non-cached push-model parser allows applications to process the types of nodes that are of interest.

− This parser uses much less memory than DOM but contains no representation of the tree. Once a node has been “pushed” to you your application is responsible for the storing of the data.

− The filter of node types is static and cannot be changed based on run-time conditions.

− All node information is pushed to the application and whether it is requested or not.

Page 20: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 10 All Rights Reserved

.NET Parsing Techniques

• .NET does not support SAX but provides three different techniques for parsing:

− XML readers and writers

− XML document editing using the DOM

− XML document editing using XPathNavigator

• XML readers provide a more effective read-only, non-cached, forward-only parser.

− This pull-model parser allows the application to control parser by specifying which nodes are of interest.

− Saves processing time because only requested nodes are sent to the application.

− XmlWriter supports generating a stream of XML content.

• The XmlDocument class implements DOM Level 2 functionality.

• XPathNavigator provides an editable, cursor-style API for reading and editing XML documents.

− In .NET 1.1, this class was read-only, but write capability is now available with .NET 2.0.

− This model is typically more useable than the DOM approach.

Page 21: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 11 All Rights Reserved

Parsing Example

• The following code example found in SimpleXML shows the use of the .NET forward scanning pull-model non-cached parser.

XmlTextReader tr = new XmlTextReader("NewCarLot.xml");

Console.WriteLine("XmlTextReader Demo Function"); Console.WriteLine("==========================="); while ( tr.Read() ) { if ( tr.NodeType == XmlNodeType.Element ) { Console.Write("Node Name:" + tr.Name); Console.WriteLine(" Attribute Count:" + tr.AttributeCount.ToString()); } } tr.Close();

• The output of the code is as follows XmlTextReader Demo Function =========================== Node Name:Dealership Attribute Count:1 Node Name:Car Attribute Count:0 Node Name:Make Attribute Count:0 Node Name:Model Attribute Count:0 Node Name:Year Attribute Count:0 Node Name:VIN Attribute Count:0 Node Name:Color Attribute Count:0 Node Name:Price Attribute Count:0

Page 22: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 12 All Rights Reserved

How Does SAX and MSXML Fit Into .NET?

• The MSXML is a COM-based component that is packaged as a set of COM classes and interfaces.

− The current version of MSXML is 6.0 and is now called “Microsoft XML Core Services Component Version 4.0.” It was released on January, 2006.

− This component is still used in VB6 applications.

− MSXML 6.0 can be used by any COM-aware programming language, including VB6, C++, and VBScript.

− It is possible to use MSXML 6.0 in .NET but the resulting code is messy.

− When programming in the .NET Framework, the XML classes are a fundamental feature and support is not an add-on anymore.

− Using the .NET Framework classes for your XML needs will make your code faster and easier to use.

• Microsoft discourages the use of SAX in C# applications because its forward-only, pull model, non-cached parsing scheme is more efficient and easier to code.

Page 23: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 13 All Rights Reserved

XmlReader and XmlWriter Features

• XmlReader and XmlWriter are the base classes that allow you to work with an XML stream.

• Because these are base classes, you can create your own custom Reader or Writer classes to access the XML stream.

• The XmlReader class represents .NET’s forward-only read-only pull-model XML parser.

− This class provides checks for well-formed XML but not validation.

− Support XML 1.0 and XML namespaces W3C standards.

− Contains the methods to navigate through document nodes, and retrieve element and attribute values.

XmlWriter XmlReader

System.Object

XmlValidatingReader

XmlTextReader

XmlNodeReader

XmlTextWriter

Page 24: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 14 All Rights Reserved

XmlReader and XmlWriter Features

• The XmlTextReader, XmlNodeReader and XmlValidatingReader classes are derived from XmlReader class.

− These classes provide different implementation for parsing your XML streams, as we’ll see later.

• The XmlWriter class has the properties and methods to create a well-formed and valid XML stream.

− You’ll find a multitude of WriteXXX functions such as WriteAttributes, WriteStartDocument, WriteNode, etc.

Page 25: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 15 All Rights Reserved

XmlTextWriter Demo

• In this demo we create the XML file that we read in earlier code. This code is found in the SimpleXML project.

XmlTextWriter tw = new XmlTextWriter("NewCarLot.xml", null); tw.Formatting = Formatting.Indented; //Opens the document tw.WriteStartDocument(); //Write comments tw.WriteComment("A lot of cars!"); //Write first element tw.WriteStartElement("Dealership"); tw.WriteAttributeString("name", "Cars R Us"); tw.WriteStartElement("Car"); //Write the Make of the Car element tw.WriteStartElement("Make"); tw.WriteString("AMC"); tw.WriteEndElement(); //Write one more element tw.WriteStartElement("Model"); tw.WriteString("Pacer"); tw.WriteEndElement(); //... Shortened for brevity tw.WriteStartElement("Price"); tw.WriteString("3998.99"); tw.WriteEndElement(); tw.WriteEndElement(); // end of car tw.WriteEndElement(); // end of dealership tw.WriteEndDocument(); tw.Close(); // close writer

Page 26: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 16 All Rights Reserved

XmlTextWriter Demo (Cont’d)

• This demo creates the “NewCarLot.xml” file in the SimpleXml directory.

− To make XML files easy to find, we often adjust the project settings so that the executable will be built in the source directory, and we keep XML files there too.

<?xml version="1.0"?> <!--A lot of cars!--> <Dealership name="Cars R Us"> <Car> <Make>AMC</Make> <Model>Pacer</Model> <Year>1977</Year> <VIN>CZ7821</VIN> <Color>Blue</Color> <Price>3998.99</Price> </Car> </Dealership>

Page 27: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 17 All Rights Reserved

.NET DOM Parser Features

• The XmlReader and XmlWriter classes aren’t resource demanding but they lack the ability to move around or modify the XML stream.

• The XmlDocument class is resource intensive because it stores the parsed XML internally offering you the advantages to navigate, modify, or create the data.

• The downside is the resources used on the machine will be proportional to the size of the entire XML stream you’ve read or are creating.

• The DOM is a language-independent W3C specification; Microsoft’s XmlDocument class implementation has many of the same property and methods (with some extensions).

• The XmlNode class, like the DOM Node interface, specifies the basic functionality for the different types of nodes in an XML stream.

Page 28: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 18 All Rights Reserved

XmlDocument Demo

• The following code, found in the SimpleXML project in the method ParseWithTheDOM, reads the XML file created in the previous demo. This code uses the DOM parser with the XmlNode class.

XmlDocument doc = new XmlDocument(); doc.Load("newCarLot.xml"); XmlNode root = doc.DocumentElement; XmlNodeList list = root.SelectNodes("//*"); foreach ( XmlNode elem in list ) { Console.WriteLine( elem.Name); }

• The output is: Dealership Car Make Model Year VIN Color Price

Page 29: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 19 All Rights Reserved

Demo – Testing Parser Features

• We’ll now work through a simple demonstration of instantiating and querying the XmlTextReader parser for some of its features.

− The demo code is in and under Demos\ParserTest —do your work in this directory. The starting code is backed up in ParserTest.

− This will also present an opportunity to prove the environment and tools setup for your machine.

1. Start Visual Studio.

2. Load project ParserTest.sln.

3. Open form Form1.cs.

Page 30: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 20 All Rights Reserved

Demo – Testing Parser Features

4. Examine the code in doXmlReaderParserTest. It asks the XmlTextReader parser what features it supports, by calling methods and properties.

XmlTextReader r = new XmlTextReader("CarLot.xml"); r.MoveToContent(); textBox1.AppendText("Can Resolve Entities: " +

r.CanResolveEntity.ToString() + Environment.NewLine);

textBox1.AppendText("Read State: " +

r.ReadState.ToString() + Environment.NewLine);

textBox1.AppendText("End of File: " +

r.EOF.ToString() + Environment.NewLine);

textBox1.AppendText("Current encoding " + r.Encoding.ToString() +

Environment.NewLine); textBox1.AppendText("Current xml:lang scope: " + r.XmlLang.ToString() +

Environment.NewLine);

textBox1.AppendText("Current xml:space scope: " + r.XmlSpace.ToString() + Environment.NewLine);

Page 31: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 21 All Rights Reserved

Demo – Testing Parser Features

5. Run the application using F5 and check out result from doXmlReaderParserTest.

6. Now, what have we just learned? By default the parser will not resolve entities; it is in an interactive read state; the parser is not at the end of the file; the encoding is UTF8; language is English; and the parser will preserve whitespace.

Page 32: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 22 All Rights Reserved

Demo – Testing Parser Features

7. What about the DOM? Take a look at doDOMParserTest:

void doDOMParserTest() { label1.Text = "DOM Parser Properties"; XmlDocument oDomParser = new XmlDocument(); bool hasFeature; hasFeature = oDomParser.Implementation.HasFeature( "XML", "1.0"); textBox1.AppendText( "XML 1.0 : " + hasFeature.ToString() + Environment.NewLine); hasFeature = oDomParser.Implementation.HasFeature( "XML", "2.0"); textBox1.AppendText( "XML 2.0 : " + hasFeature.ToString() + Environment.NewLine) ; }

8. Remove the comment before doDOMParserTest, and place a

comment before doXmlReaderParserTest. Then Run the project. The result from doDOMParserTest shows the DOM parser is created successfully.

Page 33: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 23 All Rights Reserved

Other XML Features in .NET

• XML serialization converts the state of an object into an XML byte stream suitable for persisting or transporting.

− .NET supports XML serialization in the namespace System.Xml.XmlSerialization.

• The foundation of XML serialization is XML Schema, which is a W3C Recommendation.

− XML Schema is a complete type system.

− .NET supports reading and writing XML Schema in the namespace System.Xml.Schema.

• ADO.NET is tightly coupled to XML.

− You can exchange both data and schema information between XML and DataSets.

− Support is provided in the System.Data namespace.

− Classes such as DataSet have explicit methods for working with XML data.

• XPath provides a mechanism to query for content in an XML document.

− .NET support is provided in System.Xml.XPath.

• XSLT enables transformation of XML into text, HTML or other XML.

− .NET support is provided in System.Xml.Xsl.

Page 34: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 24 All Rights Reserved

XML and the Web

• A major motivation for the development of XML was to support Web applications.

• Both XML and HTML are based on SGML, which was quite complex.

− HTML is quite simple, but is only concerned with presentation. Also, although similar to XML, it does not conform to precise XML syntax.

− XML is also simple and is concerned with the information content of a document without regard to presentation.

− XHTML is a markup language understood by modern browsers that is HTML with precise XML syntax.

• A robust way to manage complex information in a Web site is through XML, with transformation to HTML as needed for presentation.

− XSLT is an XML technology that supports transformation of XML to HTML and other formats through a stylesheet.

− There are many other ways to integrate XML with a Web site, including its use in data management, configuration, and Web services.

Page 35: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 25 All Rights Reserved

Internet Explorer and XML

• The basic Microsoft Web tool is the Internet Explorer Web browser.

• It will display well-formed XML in a collapsible tree view.

• Through a style sheet it can format XML.

Page 36: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 1

Rev. 2.1 Copyright © 2006 Object Innovations 26 All Rights Reserved

Summary

• XML parsing is the cornerstone of .NET Framework application development. Many higher-level application capabilities can make use of XML enabled features:

− Cached/Non-cached, push model, syntax/validating type parsers available

− XML object serialization

− XML messaging, for instance using SOAP

• Also, there are a number of XML-related specifications that define their own “languages,” or really their own XML vocabularies – examples are XSLT and XML Schema.

− Each of these allows some information to be defined in an XML document: an XSLT style sheet or transform, an XML Schema.

− Because these each leverage basic XML, the style sheets and schema can themselves be parsed and manipulated, just like any other XML document.

• Microsoft provides the XML functionality, thereby allowing .NET compliant programming languages to share the same XML parsing engine.

• XML is tightly integrated with ADO.NET.

Page 37: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 103 All Rights Reserved

Chapter 4

Writing XML Streams in .NET

Page 38: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 104 All Rights Reserved

Writing XML Streams in .NET

Objectives

After completing this unit you will be able to:

• Understand the functionality of the XmlWriter class.

• Use the XmlTextWriter class to create well-formed XML documents.

• Create XmlWriters in .NET 2.0 using an XmlWriterSettings object and the Create() method of the XmlWriter class.

• Describe the possible states of an XmlWriter.

• Use the write methods to write simple and complex element tags.

• Create attributes and elements with namespaces and prefixes.

• Create attributes with concatenated values.

Page 39: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 105 All Rights Reserved

Writing XML in .NET

• Rarely do you write out XML by hand. You generally write XML out in a stream based on input or database information.

• In the past, creating files of XML was painful programming.

− Ensuring attributes were quoted, elements had starting and ending tags and such could be error prone.

• In the .NET Framework, the XmlWriter classes allow us to create well-formed XML streams.

− These classes give us the ability to write out declarations, elements, attributes, comments, etc. in a well-formed manner.

• In addition to creating XML nodes, the XmlWriter classes have the ability to write out large segments of information, including binary data such as JPEG.

Page 40: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 106 All Rights Reserved

The XmlWriter Class

• The XmlWriter class is a base class that defines the methods for all XmlWriters to implement.

− In .NET 2.0, XmlWriter has a static Create() method, similar to the Create() method for XmlReader.

• .NET 1.x provided the XmlTextWriter class, which still works, though using XmlWriter and the Create() method is now preferred.

• The XmlWriter classes ensure that data written out is well-formed and conforms to the W3C specifications on XML and Namespaces.

• To summarize, the XmlWriter will allow us to:

− Create well formed documents

− Ensure proper namespace usage

− Allow us to encode the data as text or binary

− Write the data to whichever stream type you choose i.e. file, config file, HTTP response, etc.

− Write out all XML types

− Specify the xml:lang or xml:space usage for elements

Page 41: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 107 All Rights Reserved

The XmlWriter Class (Cont’d)

• We will see later that the DOM allows us to write XML streams as well, but the XmlWriter class is more efficient because it has less memory management issues.

− The disadvantage is that you can't back up in the stream and add information to the stream.

• The paradigm for nodes in the XmlWriter is very simple. Many methods are paired, meaning they have a WriteStartXXX() and WriteEndXXX():

− WriteStartDocument() and WriteEndDocument()

− WriteStartElement() and WriteEndElement()

− WriteStartAttribute() and WriteEndAttribute()

− WriteCData(), WriteEntityRef(), WriteNmToken()

• Writing values in XmlWriter classes is done in the following ways:

− WriteElementString() to write the value of an Element

− WriteAttributeString() to write the value of an Attribute

− WriteString() to write a string value

− WriteNode() writes the given text content.

• There are more write methods found in the MSDN on XmlWriter.

Page 42: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 108 All Rights Reserved

WriteMovie Example

• Our first example program is in WriteMovie. static void Main(string[] args) { XmlTextWriter xmlw = new XmlTextWriter( "Catch22.xml", Encoding.UTF8); xmlw.Formatting = Formatting.Indented; xmlw.WriteStartDocument(); xmlw.WriteComment("Catch22 movie info"); xmlw.WriteStartElement("Movie"); xmlw.WriteStartElement("Title"); xmlw.WriteString("Catch22"); xmlw.WriteEndElement(); xmlw.WriteStartElement("Review"); xmlw.WriteString("3 stars"); xmlw.WriteEndElement(); xmlw.WriteStartElement("Rating"); xmlw.WriteString("R"); xmlw.WriteEndElement(); xmlw.WriteEndElement(); // Movie xmlw.WriteEndDocument(); // Close the writer xmlw.Close(); }

− The Catch32.xml will be created.

<?xml version="1.0"?> <!--Catch22 movie info--> <Movie> <Title>Catch22</Title> <Review>3 stars</Review> <Rating>R</Rating> </Movie>

Page 43: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 109 All Rights Reserved

The XmlTextWriter Class

• The XmlTextWriter is an implementation of the XmlWriter.

• To create an XmlTextWriter we have three ways of creating it using a TextWriter instance, stream instance, or name of a file.

• The following code creates an XmlTextWriter file named Catch22.xml on disk.

XmlTextWriter xmlw = new XmlTextWriter( "Catch22.xml", Encoding.UTF8);

• Before writing any data out to the XML stream, change the formatting if humans will be looking at it.

xmlw.Formatting = Formatting.Indented;

• The first and last methods to call to create an XML document are

xwrtr.WriteStartDocument(); //call at beginning ... xwrtr.WriteEndDocument(); //call at the end

• The WriteStartDocument method writes out the XML declaration in the stream.

<?xml version="1.0" encoding="utf-8"?>

• Now you begin the task of creating the XML stream using the other various WriteXXX() methods.

Page 44: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 110 All Rights Reserved

The State of Writer

• The XmlWriter has a read-only property called WriteState that indicates the context of the current write operation.

• As you call the various WriteXXX() methods the WriteState changes values.

State Description

Start Once the XmlWriter has been created.

Prolog The XML prolog has been written with WriteStartDocument.

Element An element is being written. WriteStartElement has been called.

Attribute An attribute is currently being written.

Content The opening tag content is being written.

Epilog Internal use only. Once the root element has been closed.

Closed The writer is closed by a call to WriteEndDocument.

• The XmlWriter will throw exceptions if you attempt to write illegal XML. For example, writing an attribute without first writing an element tag.

Page 45: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 111 All Rights Reserved

Creating XmlWriters in .NET 2.0

• In .NET 2.0 it is recommended that you create XmlWriters using the static Create() method.

− This new approach is illustrated in the WriteMovie20 example.

• Instead of creating a special kind of writer, such as XmlTextWriter, you specify the features of the writer you want created in an XmlWriterSettings object.

XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; settings.Indent = true; settings.IndentChars = " "; // default is two spaces XmlWriter xmlw = XmlWriter.Create("Catch22.xml", settings); xmlw.WriteStartDocument(); xmlw.WriteComment("Catch22 movie info"); xmlw.WriteStartElement("Movie"); xmlw.WriteStartElement("Title"); xmlw.WriteString("Catch22"); xmlw.WriteEndElement(); ...

Page 46: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 112 All Rights Reserved

Lab 4A

A GUI for Writing XML

In this lab you create a GUI program for writing XML. Your program will allow you to create elements and attributes using XmlWriter.

Detailed instructions are contained in the Lab 4A write-up at the end of the chapter.

Suggested time: 30 minutes.

Page 47: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 113 All Rights Reserved

Writing Out Elements

• There are various ways of creating elements. Generally, the XmlWriter will create empty elements if there is no content.

• The easiest way to create a tag with content is xwrtr.WriteElementString("car",”A new car”);

• This results in the following XML. <car>A new car</car>

• The following code creates an empty XML tag. xwrtr.WriteStartElement("car"); //results in <car/> xwrtr.WriteEndElement();

• When you want closing tags, for example for some HTML tags, use the WriteFullEndElement() method:

xwrtr.WriteStartElement("car"); xwrtr.WriteFullEndElement(); //results in <car></car>

• To create text content for the element use the WriteString() method.

xwrtr.WriteStartElement("car"); xwrtr.WriteString("A new car for me?"); xwrtr.WriteEndElement();

• This results in the following XML: <car>A new car for me?</car>

Page 48: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 114 All Rights Reserved

Writing Out Elements

• WriteStartElement() is overloaded so that you can write out a prefix, tag, and a namespace.

xwrtr.WriteStartElement("oi", "car", "http://www.objectinnovations.com/ns"); xwrtr.WriteString("A new car for me?"); xwrtr.WriteEndElement();

• This results in <oi:car xmlns:oi="http://www.objectinnovations.com/ns"> A new car for me? </oi:car>

• Elements then written inside the context of the element will have the prefix defined for it. If you want to use the prefix for the namespace, you are required to explicitly put it into the name.

xwrtr.WriteStartElement("oi:make");

• To create a default namespace for the tag and its child elements leave the prefix blank.

xwrtr.WriteStartElement("", "car", "http://www.objectinnovations.com/ns");

• This results in <car xmlns="http://www.objectinnovations.com/ns">

Page 49: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 115 All Rights Reserved

Writing Nested Elements

• Elements that contain child elements will have multiple WriteStartElement() calls. This makes nested elements.

• To conclude an element, call WriteEndElement() an equivalent number of times. The following sample is found in WritingExamples.

xwrtr.WriteStartElement("cars"); xwrtr.WriteStartElement("name"); xwrtr.WriteString("Midsize"); xwrtr.WriteEndElement(); // name // Another car xwrtr.WriteStartElement("name"); xwrtr.WriteString("Truck"); xwrtr.WriteEndElement(); // name xwrtr.WriteEndElement(); // cars

• This will result in XML that looks like the following. <cars> <name>Midsize</name> <name>Truck</name> </cars>

Page 50: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 116 All Rights Reserved

Writing Attributes

• The most simple way to write attributes is WriteAttributeString(). This method will write the attribute name, prefix, and value and close the attribute string.

• This code will create the following XML. xwrtr.WriteStartElement("cars"); xwrtr.WriteAttributeString("Owner",

"Bill Smith"); xwrtr.WriteAttributeString("Value", "$10000");

• This will result in XML that looks like the following. <cars Owner="Bill Smith" Value="$10000">

• To write more complex attributes, for example when the attributes are optional and not known at compile time or when you must concatenate use WriteStartAttribute() and WriteEndAttribute().

− WriteStartAttribute() has two overloaded methods one allows you to write the attribute value with the namespace and the other allows you specify the prefix, the attribute name, and a namespace.

− WriteEndAttribute() must be called to specify the end of an attribute value no matter which WriteStartAttribute() method you call.

Page 51: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 117 All Rights Reserved

Writing Attributes

• Here is an example of concatenating an entity character to a attribute string value. Again, this code is found in WritingExamples.

xwrtr.WriteStartAttribute("", "cost", ""); xwrtr.WriteCharEntity('\u0024'); // The $ character xwrtr.WriteString("5000"); xwrtr.WriteEndAttribute();

• This results in the following XML. <name cost="&#x24;5000">

• A shortcut exists in the use of WriteAttributeString(), WriteStartAttribute() or WriteEndElement(): these functions automatically close the preceding attribute value for you.

xwrtr.WriteStartElement("name") xwrtr.WriteStartAttribute("", "cost", "") xwrtr.WriteString("$5000") //xwrtr.WriteEndAttribute() //not needed closed

//automatically xwrtr.WriteAttributeString("manufacturer", "",

"Toyota") xwrtr.WriteString("Truck") xwrtr.WriteEndElement() 'name

• This results in the following XML. <name cost="$5000" manufacturer="Toyota">Truck </name>

Page 52: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 118 All Rights Reserved

Lab 4B

Create a Print Order

In this lab you will continue the Zenith Courseware case study by writing a program to read a purchase order and write a print order. The starting code is based on the previous case study code that parses a purchase order. You need to modify the program so that instead of creating a simple text report of the purchase order, it writes the XML for a print order.

Detailed instructions are contained in the Lab 4B write-up at the end of the chapter.

Suggested time: 45 minutes.

Page 53: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 119 All Rights Reserved

Summary

• The XmlWriter allows you to easily create XML streams.

− It has write methods to create every type of XML node type.

− It ensures that data written out is well formed and conforms to the W3C specification on XML.

− It allows you to create complex tags with nested content.

− It gives you complete control over namespaces.

• In .NET 2.0, you can create XmlWriters using an XmlWriterSettings object and the Create() method of the XmlWriter class.

Page 54: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 120 All Rights Reserved

Lab 4A

A GUI for Writing XML

Introduction In this lab you will create a GUI program for writing XML. Your program will allow the user to create elements and attributes. Suggested Time: 30 minutes. Root Directory: OIC\XmlCs Directories: Labs\Lab4A\WritingDemo (do your work here)

Chap04\WritingDemo\Step0 (backup of starter files) Chap04\WritingDemo\Step1 (answer to Part 1) Chap04\WritingDemo\Step2 (answer to Part 2)

Files: Form1.cs

Instructions – Part 1 1. Open the starter project. You are provided a GUI for writing XML.

Page 55: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 121 All Rights Reserved

2. Provide using statements for the namespaces System.Xml and System.IO.

3. Declare a private member variable m_xwrtr of type XmlWriter.

4. Locate the method StartDoc(). In this function initialize your XmlWriter using a stream opened for sharing using the following code.

XmlWriterSettings settings = new XmlWriterSettings(); FileStream stream = new FileStream("Example.xml", FileMode.Create, FileAccess.Write, FileShare.ReadWrite); m_xwrtr = XmlWriter.Create(stream, settings); 5. Call WriteStartDocument to write the XML declaration in your StartDoc function.

6. Add handlers for Write Start Element, Write End Element and End Document and call the appropriate XmlWriter method WriteStartElement(), WriteEnd-Element(), and WriteEndDocument(), respectively. Be sure to close the XmlWriter when all done. Experiment with creating some small XML documents using only what you have implemented so far. Run the program and examine the file Example.xml.

7. Notice that everything is written on one line. Enhance StartDoc() to specify indented formatting, and you may specify the indenting characters. Run the program again.

XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = " "; ... 8. Add handlers for Write Comment, Write String, Write Attribute String and Start

Document calling the XmlWriter methods WriteComment(), WriteStringElement(), WriteAttributeString(), and WriteStartDocument(), respectively. Run the program a number of times, creating a variety of XML documents.

Instructions – Part 2 As you ran the Part 1 version of the program, you probably noticed that if you performed writing operations in the wrong order you would get an exception. Also, the only way to see the results of your writing was to open the file Example.xml, either in a text editor or in a browser. Now you will use a multi-line textbox txtMessage for showing output, which can be used either for displaying exception messages or for showing the file that has been created.

Page 56: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 122 All Rights Reserved

1. Add code to the helper method ReadDoc() which will read the file Example.xml and

display it in the textbox. (See code below if you need it.) Build and run, and try to duplicate the operations that will result in the XML document shown. Be sure and flush the writer before calling ReadDoc().

2. Add exception handlers for the buttons. This will display exception messages in the textbox. Experiment with various exception conditions.

3. Create a label at the bottom of Form1 to display the current state of the XmlWriter. After each WriteXXX in the button handlers update the text of the label to the property WriteState.

Code for ReadDoc() helper method.

private void ReadDoc() { txtMessage.Text = ""; FileStream fstream = File.Open("Example.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); StreamReader reader = new StreamReader(fstream); txtMessage.Text = reader.ReadToEnd(); reader.Close(); fstream.Close(); }

Page 57: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 123 All Rights Reserved

Lab 4B

Create a Print Order

Introduction In this lab you will continue the Zenith Courseware case study by writing a program to read a purchase order and write a print order. The starting code is based on the previous case study code that parses a purchase order. You need to modify the program so that instead of creating a simple text report of the purchase order, it writes the XML for a print order. The print order document has a root element <printOrder> with the same attributes as the <purchaseOrder> element in the input document. The PO elements <customer> and <billTo>, pertaining to the customer of the training company, are deleted in the print order. The <destinations> element and children are the same.

Suggested Time: 45 minutes. Root Directory: OIC\XmlCs Directories: Labs\Lab4B\WritePrintOrder (do your work here) CaseStudy\WritePrintOrder\Step0 (backup copy of starter files) CaseStudy\WritePrintOrder\Step1 (answer)

Page 58: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 124 All Rights Reserved

Instructions 1. Build and run the starter program. It is basically the same as Step 5 of the ParsePO

program, with the GUI elements labeled slightly differently to reflect the purpose of the new program. Also, the output of the stream writer is hardcoded to output.txt. We will be writing the output XML file to the file named in the textbox with the label “Print Order.” When we are all done, we will delete the parsing output to output.txt.

2. In the Parse() method delete the cases for “customer” and “billTo,” and remove the Customer() method. Build and run.

3. Declare a private member variable wr of type XmlWriter.

4. Add code after the validating reader has been set up to initialize wr to a new XmlWriter with file name specified in the combobox, set the formatting to be indented, and call the WriteStartDocument() method.

XmlWriterSettings wrset = new XmlWriterSettings(); wrset.Indent = true; wr = XmlWriter.Create(txtOutput.Text, wrset); wr.WriteStartDocument(); 5. In the finally clause add code to call WriteEndDocument () and close the writer.

Build and run.

6. You will get an error because no root element has been created. After the call to WriteStartDocument() call wr.WriteStartElement("printOrder").

7. Build and run. You should now get a minimal well-formed XML document created.

8. Replace the code in PurchaseOrder() by code to read the two specific attributes “poNumber” and “orderDate” and write out these attribute strings to the XML file. Build and run. (Note that you will first have to pass over the attributes “xmlns:xsi” and “xsi:noNamespaceSchemaLocation” associated with schema validation.)

9. In the Destinations() method, add a call at the beginning to write out a “destinations” start element and code at the end to write out an end element. You can incrementally build and test at each point, but we won’t specifically say so any longer.

10. In Destination() add a call at the beginning to write out a “destination” start element and code at the end to write out an end element.

11. Add code to Destination() to write out the attribute string. You can also delete the old code that writes to output.txt.

12. In Destination() change the “shipTo” case to call a method ShipTo(), and change the name of ShowAddress() to ShipTo(). You may remove the label parameter.

Page 59: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 125 All Rights Reserved

13. Modify the code in ShipTo() to write a start element, write element strings, and then write an end element.

14. Modify the code in Courses() to write a start element and an end element.

15. Modify the code in Course() to write a start element, an attribute, element strings, and an end element.

16. Build and test. You should now be able to write out a complete print order XML document.

17. As a final touch, write out the attributes for the root element that will set up schema validation against the file printOrder.xsd. You will have to use an overloaded WriteAttributeString() method, as the standard method does not like the colon character in an attribute name.

18. Remove any residual code pertaining to creating the output.txt file.

19. Test with various input purchase order documents, and make sure that the validating parsing code is still working.

20. As a final exercise, run the Validate.exe tool to verify that the print order XML files you have created are valid against the printOrder.xsd file.

Page 60: XML Parsing Using C# and · XML Parsing Using C# and .NET Rev. 2.1 ... 414, XML Programming Using C# and .NET Student Guide Information in this document is subject to change without

XmlCs Chapter 4

Rev. 2.1 Copyright © 2006 Object Innovations 126 All Rights Reserved