100% found this document useful (1 vote)
959 views

Beginning XML with C# 7: XML Processing and Data Access for C# Developers 2nd Edition Bipin Joshi (Auth.) 2024 scribd download

Beginning

Uploaded by

hindsrymaluh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
959 views

Beginning XML with C# 7: XML Processing and Data Access for C# Developers 2nd Edition Bipin Joshi (Auth.) 2024 scribd download

Beginning

Uploaded by

hindsrymaluh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Download the Full Version of textbook for Fast Typing at textbookfull.

com

Beginning XML with C# 7: XML Processing and Data


Access for C# Developers 2nd Edition Bipin Joshi
(Auth.)

https://textbookfull.com/product/beginning-xml-with-c-7-xml-
processing-and-data-access-for-c-developers-2nd-edition-
bipin-joshi-auth/

OR CLICK BUTTON

DOWNLOAD NOW

Download More textbook Instantly Today - Get Yours Now at textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

C# and XML Primer 1st Edition Jonathan Hartwell (Auth.)

https://textbookfull.com/product/c-and-xml-primer-1st-edition-
jonathan-hartwell-auth/

textboxfull.com

Java XML and JSON: Document Processing for Java SE 2nd


Edition Jeff Friesen

https://textbookfull.com/product/java-xml-and-json-document-
processing-for-java-se-2nd-edition-jeff-friesen/

textboxfull.com

Java XML and JSON: Document Processing for Java SE Jeff


Friesen

https://textbookfull.com/product/java-xml-and-json-document-
processing-for-java-se-jeff-friesen/

textboxfull.com

Java XML and JSON Friesen Jeff

https://textbookfull.com/product/java-xml-and-json-friesen-jeff/

textboxfull.com
Beginning C 7 Programming with Visual Studio 2017 1st
Edition Benjamin Perkins

https://textbookfull.com/product/beginning-c-7-programming-with-
visual-studio-2017-1st-edition-benjamin-perkins/

textboxfull.com

Beginning C 7 Hands On The Core Language Tom Owsiak

https://textbookfull.com/product/beginning-c-7-hands-on-the-core-
language-tom-owsiak/

textboxfull.com

Beginning Database Programming Using ASP NET Core 3 With


MVC Razor Pages Web API jQuery Angular SQL Server and
NoSQL 1st Edition Bipin Joshi
https://textbookfull.com/product/beginning-database-programming-using-
asp-net-core-3-with-mvc-razor-pages-web-api-jquery-angular-sql-server-
and-nosql-1st-edition-bipin-joshi/
textboxfull.com

Pro RESTful APIs: Design, Build and Integrate with REST,


JSON, XML and JAX-RS Patni

https://textbookfull.com/product/pro-restful-apis-design-build-and-
integrate-with-rest-json-xml-and-jax-rs-patni/

textboxfull.com

Data Structures with C Programming 2nd Edition Anil Kumar


Yadav

https://textbookfull.com/product/data-structures-with-c-
programming-2nd-edition-anil-kumar-yadav/

textboxfull.com
Beginning
XML with C# 7
XML Processing and Data Access for
C# Developers

Second Edition

Bipin Joshi
Beginning XML with C# 7
XML Processing and
Data Access for C# Developers

Second Edition

Bipin Joshi
Beginning XML with C# 7: XML Processing and Data Access for C# Developers
Bipin Joshi
301 Pitruchhaya, Thane, India
ISBN-13 (pbk): 978-1-4842-3104-3 ISBN-13 (electronic): 978-1-4842-3105-0
https://doi.org/10.1007/978-1-4842-3105-0
Library of Congress Control Number: 2017961825
Copyright © 2017 by Bipin Joshi
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are
not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Cover image by Freepik (www.freepik.com)
Managing Director: Welmoed Spahr
Editorial Director: Todd Green
Acquisitions Editor: Steve Anglin
Development Editor: Matthew Moodie
Technical Reviewer: Michael Thomas
Coordinating Editor: Mark Powers
Copy Editor: Kezia Endsley
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring
Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail
orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC
and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc).
SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail rights@apress.com, or visit http://www.apress.com/
rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions
and licenses are also available for most titles. For more information, reference our Print and eBook Bulk
Sales web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book's product page, located at www.apress.com/9781484231043. For more
detailed information, please visit http://www.apress.com/source-code.
Printed on acid-free paper
This work is dedicated to Lord Shiva, who, I believe,
resides in each one of us as pure consciousness.
Contents

About the Author���������������������������������������������������������������������������������������������������xvii


About the Technical Reviewer��������������������������������������������������������������������������������xix
Introduction������������������������������������������������������������������������������������������������������������xxi


■Chapter 1: Introducing XML and the .NET Framework������������������������������������������ 1
What Is XML?������������������������������������������������������������������������������������������������������������������� 1
Benefits of XML�������������������������������������������������������������������������������������������������������������������������������������� 2
XML-Driven Applications������������������������������������������������������������������������������������������������������������������������ 3

Rules of XML Grammar���������������������������������������������������������������������������������������������������� 5


Markup Is Case Sensitive����������������������������������������������������������������������������������������������������������������������� 6
A Document Must Have One and Only One Root Element���������������������������������������������������������������������� 6
A Start Tag Must Have an End Tag���������������������������������������������������������������������������������������������������������� 6
Start and End Tags Must Be Properly Nested����������������������������������������������������������������������������������������� 7
Attribute Values Must Be Enclosed in Quotes����������������������������������������������������������������������������������������� 7

DTD and XML Schema������������������������������������������������������������������������������������������������������ 7


Parsing XML Documents�������������������������������������������������������������������������������������������������� 8
XSLT���������������������������������������������������������������������������������������������������������������������������������� 9
XPath������������������������������������������������������������������������������������������������������������������������������ 10
The .NET Framework������������������������������������������������������������������������������������������������������ 11
.NET Framework and XML���������������������������������������������������������������������������������������������� 12
Assemblies and Namespaces��������������������������������������������������������������������������������������������������������������� 13
The Classic XML Parsing Model of the .NET Framework���������������������������������������������������������������������� 14
The LINQ-Based Parsing Model of the .NET Framework���������������������������������������������������������������������� 14
.NET Configuration Files����������������������������������������������������������������������������������������������������������������������� 15

v
■ Contents

ADO.NET������������������������������������������������������������������������������������������������������������������������������������������������ 17
ASP.NET Web Forms Server Controls���������������������������������������������������������������������������������������������������� 17
XML Serialization���������������������������������������������������������������������������������������������������������������������������������� 18
Web Services, WCF Services, and Web API������������������������������������������������������������������������������������������� 19
XML Documentation����������������������������������������������������������������������������������������������������������������������������� 19
XAML Markup��������������������������������������������������������������������������������������������������������������������������������������� 21
SQL Server XML Features��������������������������������������������������������������������������������������������������������������������� 21

Working with Visual Studio��������������������������������������������������������������������������������������������� 21


Creating Windows Forms Applications������������������������������������������������������������������������������������������������� 22
Creating Class Libraries������������������������������������������������������������������������������������������������������������������������ 25

Summary������������������������������������������������������������������������������������������������������������������������ 28

■Chapter 2: Manipulating XML Documents Using the Document Object Model����� 29
Using the DOM Parser���������������������������������������������������������������������������������������������������� 29
Knowing When to Use DOM�������������������������������������������������������������������������������������������� 31
A Sample XML Document����������������������������������������������������������������������������������������������� 32
Opening an Existing XML Document for Parsing������������������������������������������������������������ 33
Navigating Through an XML Document�������������������������������������������������������������������������� 35
Looking for Specific Elements and Nodes���������������������������������������������������������������������� 36
Retrieving Specific Elements Using the GetElementsByTagName() Method���������������������������������������� 37
Retrieving Specific Elements Using the GetElementById() Method������������������������������������������������������ 38
Selecting Specific Nodes Using the SelectNodes() Method������������������������������������������������������������������ 41
Selecting a Single Specific Node Using the SelectSingleNode() Method��������������������������������������������� 43

Modifying XML Documents�������������������������������������������������������������������������������������������� 44


Navigating Between Various Nodes������������������������������������������������������������������������������������������������������ 45
Modifying Existing Content������������������������������������������������������������������������������������������������������������������� 46
Deleting Existing Content��������������������������������������������������������������������������������������������������������������������� 47
Adding New Content����������������������������������������������������������������������������������������������������������������������������� 48
Using Helper Methods�������������������������������������������������������������������������������������������������������������������������� 50

Dealing with Whitespace������������������������������������������������������������������������������������������������ 50

vi
■ Contents

Dealing with Namespaces���������������������������������������������������������������������������������������������� 54


Understanding Events of the XmlDocument Class��������������������������������������������������������� 55
Summary������������������������������������������������������������������������������������������������������������������������ 58

■Chapter 3: Reading and Writing XML Documents������������������������������������������������ 59
What Are XML Readers and Writers?������������������������������������������������������������������������������ 59
When to Use Readers and Writers���������������������������������������������������������������������������������� 60
Reader Classes��������������������������������������������������������������������������������������������������������������� 60
The XmlTextReader Class��������������������������������������������������������������������������������������������������������������������� 60
The XmlValidatingReader Class������������������������������������������������������������������������������������������������������������ 60
The XmlNodeReader Class������������������������������������������������������������������������������������������������������������������� 60

Reading XML Documents Using XmlTextReader������������������������������������������������������������ 61


Opening XML Documents��������������������������������������������������������������������������������������������������������������������� 61
Reading Attributes, Elements, and Values�������������������������������������������������������������������������������������������� 63
Improving Performance by Using Name Tables������������������������������������������������������������������������������������ 65
Dealing with Namespaces�������������������������������������������������������������������������������������������������������������������� 66

Moving Between Elements��������������������������������������������������������������������������������������������� 66


The ReadSubTree() Method������������������������������������������������������������������������������������������������������������������ 66
The ReadToDescendant() Method��������������������������������������������������������������������������������������������������������� 67
The ReadToFollowing() Method������������������������������������������������������������������������������������������������������������ 67
The ReadToNextSibling() Method���������������������������������������������������������������������������������������������������������� 68
The Skip() Method�������������������������������������������������������������������������������������������������������������������������������� 68

Moving Between Attributes�������������������������������������������������������������������������������������������� 69


Reading Content������������������������������������������������������������������������������������������������������������� 69
The ReadInnerXml() Method����������������������������������������������������������������������������������������������������������������� 70
The ReadOuterXml() Method����������������������������������������������������������������������������������������������������������������� 70
The ReadString() Method���������������������������������������������������������������������������������������������������������������������� 70

Writing XML Documents Using XmlTextWriter���������������������������������������������������������������� 71


Exporting Columns As Elements����������������������������������������������������������������������������������������������������������� 75
Exporting Columns As Attributes���������������������������������������������������������������������������������������������������������� 75
Specifying Character Encoding������������������������������������������������������������������������������������������������������������ 75

vii
■ Contents

Formatting the Output�������������������������������������������������������������������������������������������������������������������������� 76


Including Namespace Support������������������������������������������������������������������������������������������������������������� 78

Dealing with Nontextual Data����������������������������������������������������������������������������������������� 81


Serializing Data������������������������������������������������������������������������������������������������������������������������������������ 82
Deserializing Data��������������������������������������������������������������������������������������������������������������������������������� 83

Summary������������������������������������������������������������������������������������������������������������������������ 84

■Chapter 4: Accessing XML Documents Using the XPath Data Model������������������� 85
Overview of XPath���������������������������������������������������������������������������������������������������������� 85
Location Path���������������������������������������������������������������������������������������������������������������������������������������� 86
Axis������������������������������������������������������������������������������������������������������������������������������������������������������� 86
Node Tests�������������������������������������������������������������������������������������������������������������������������������������������� 86
Predicates��������������������������������������������������������������������������������������������������������������������������������������������� 87
Putting It All Together��������������������������������������������������������������������������������������������������������������������������� 87
XPath Functions������������������������������������������������������������������������������������������������������������������������������������ 87

The XPath Data Model���������������������������������������������������������������������������������������������������� 89


Creating XPathNavigator����������������������������������������������������������������������������������������������������������������������� 89
Navigating an XML Document Using XPathNavigator��������������������������������������������������������������������������� 90
Selecting Nodes������������������������������������������������������������������������������������������������������������������������������������ 92
Navigating Between Attributes������������������������������������������������������������������������������������������������������������� 96
Retrieving Inner and Outer XML������������������������������������������������������������������������������������������������������������ 97
Getting an XmlReader from XPathNavigator����������������������������������������������������������������������������������������� 99
Getting an XmlWriter from XPathNavigator���������������������������������������������������������������������������������������� 102
Editing XML Documents with the XPathNavigator Class�������������������������������������������������������������������� 104

Summary���������������������������������������������������������������������������������������������������������������������� 109

■Chapter 5: Validating XML Documents�������������������������������������������������������������� 111
Providing Structure for XML Documents���������������������������������������������������������������������� 111
Document Type Definition (DTD)��������������������������������������������������������������������������������������������������������� 112
XML Data Reduced (XDR) Schema������������������������������������������������������������������������������������������������������ 112
XML Schema Definition (XSD) Schema����������������������������������������������������������������������������������������������� 112

Creating Structure for an XML Document�������������������������������������������������������������������� 112

viii
■ Contents

The Structure of Employees.xml��������������������������������������������������������������������������������������������������������� 112


Creating the DTD�������������������������������������������������������������������������������������������������������������������������������� 113
Creating the XML Schema������������������������������������������������������������������������������������������������������������������ 115

Creating Schemas by Using the Schema Object Model (SOM)������������������������������������� 126


The Core SOM Classes������������������������������������������������������������������������������������������������������������������������ 126
Creating an XML Schema Using the SOM������������������������������������������������������������������������������������������� 128

Attaching the DTD and XML Schemas to XML Documents������������������������������������������� 135


Inline DTDs����������������������������������������������������������������������������������������������������������������������������������������� 136
External DTDs������������������������������������������������������������������������������������������������������������������������������������� 136
Inline XML Schema����������������������������������������������������������������������������������������������������������������������������� 137
External XML Schema������������������������������������������������������������������������������������������������������������������������� 137
Adding Frequently Used Schemas to the Schema Cache������������������������������������������������������������������� 138

Using XmlReader to Validate XML Documents������������������������������������������������������������� 139


Using XmlDocument to Validate XML Documents�������������������������������������������������������� 142
Using XPathNavigator to Validate XML Documents������������������������������������������������������ 145
Specifying XML Schema via Code�������������������������������������������������������������������������������� 145
Summary���������������������������������������������������������������������������������������������������������������������� 147

■Chapter 6: Transforming XML with XSLT����������������������������������������������������������� 149
Overview of XSLT���������������������������������������������������������������������������������������������������������� 149
Applying Templates Using <xsl:apply-templates>����������������������������������������������������������������������������� 153
Branching Using <xsl:if>�������������������������������������������������������������������������������������������������������������������� 154
Branching Using <xsl:choose> and <xsl:when>������������������������������������������������������������������������������� 156
Transforming Elements and Attributes����������������������������������������������������������������������������������������������� 158

The XslCompiledTransform Class��������������������������������������������������������������������������������� 161


Performing Transformations Using XslCompiledTransform���������������������������������������������������������������� 161
Passing Arguments to a Transformation��������������������������������������������������������������������������������������������� 164
Using Script Blocks in an XSLT Style Sheet���������������������������������������������������������������������������������������� 166
Using Extension Objects��������������������������������������������������������������������������������������������������������������������� 170
Compiling XSLT Style Sheets�������������������������������������������������������������������������������������������������������������� 171

Summary���������������������������������������������������������������������������������������������������������������������� 173

ix
■ Contents


■Chapter 7: XML in ADO.NET������������������������������������������������������������������������������� 175
Overview of ADO.NET Architecture������������������������������������������������������������������������������� 175
Connected Data Access���������������������������������������������������������������������������������������������������������������������� 175
Disconnected Data Access����������������������������������������������������������������������������������������������������������������� 176
ADO.NET Data Providers��������������������������������������������������������������������������������������������������������������������� 177
ADO.NET Classes�������������������������������������������������������������������������������������������������������������������������������� 178

XML and Connected Data Access��������������������������������������������������������������������������������� 180


Using the ExecuteXmlReader() Method���������������������������������������������������������������������������������������������� 180

XML and Disconnected Data Access���������������������������������������������������������������������������� 182


Understanding DataSet����������������������������������������������������������������������������������������������������������������������� 183
Understanding DataAdapter��������������������������������������������������������������������������������������������������������������� 184
Working with DataSet and DataAdapter��������������������������������������������������������������������������������������������� 186
Saving DataSet Contents As XML������������������������������������������������������������������������������������������������������� 192
Reading XML Data into DataSet���������������������������������������������������������������������������������������������������������� 197
Generating Menus Dynamically Based On an XML File���������������������������������������������������������������������� 200
Reading Only the Schema Information����������������������������������������������������������������������������������������������� 202

Creating a Typed DataSet��������������������������������������������������������������������������������������������� 204


Using Visual Studio to Create a Typed DataSet����������������������������������������������������������������������������������� 205
Using the xsd.exe Tool to Create a Typed DataSet������������������������������������������������������������������������������ 210

Summary���������������������������������������������������������������������������������������������������������������������� 210

■Chapter 8: XML Serialization����������������������������������������������������������������������������� 211
Understanding the Flavors of Serialization������������������������������������������������������������������ 211
Classes Involved in the XML Serialization������������������������������������������������������������������������������������������ 212

Serializing and Deserializing Objects Using XmlSerializer������������������������������������������� 212


Handling Events Raised During Deserialization���������������������������������������������������������������������������������� 215
Serializing and Deserializing Complex Types������������������������������������������������������������������������������������� 217
Serialization and Inheritance�������������������������������������������������������������������������������������������������������������� 221
Customizing the Serialized XML��������������������������������������������������������������������������������������������������������� 224

x
■ Contents

Serializing and Deserializing Objects Using DataContractSerializer���������������������������� 227


Customizing the Serialized XML��������������������������������������������������������������������������������������������������������� 230

Serializing and Deserializing Objects Using SoapFormatter���������������������������������������� 231


Customizing SOAP Serialization��������������������������������������������������������������������������������������������������������� 234

Summary���������������������������������������������������������������������������������������������������������������������� 237

■Chapter 9: XML in Web Services������������������������������������������������������������������������ 239
What Are Web Services?���������������������������������������������������������������������������������������������� 239
Creating and Consuming Web Services����������������������������������������������������������������������� 240
Creating a Web Service���������������������������������������������������������������������������������������������������������������������� 241
Creating a Proxy for a Web Service���������������������������������������������������������������������������������������������������� 254
Creating a Form That Calls the Web Methods������������������������������������������������������������������������������������� 256

Understanding SOAP���������������������������������������������������������������������������������������������������� 259


Using SOAP Headers��������������������������������������������������������������������������������������������������������������������������� 260
Customizing the XML Serialization����������������������������������������������������������������������������������������������������� 264

Understanding the WSDL Document���������������������������������������������������������������������������� 265


The Messages������������������������������������������������������������������������������������������������������������������������������������� 266
The Type Definitions��������������������������������������������������������������������������������������������������������������������������� 266
The Port Types������������������������������������������������������������������������������������������������������������������������������������ 267
The Binding����������������������������������������������������������������������������������������������������������������������������������������� 267
The Service����������������������������������������������������������������������������������������������������������������������������������������� 267
A Summary of WSDL��������������������������������������������������������������������������������������������������������������������������� 267

Summary���������������������������������������������������������������������������������������������������������������������� 267

■Chapter 10: XML in WCF and Web API��������������������������������������������������������������� 269
Operations Based Services vs. Resource Based Services������������������������������������������� 270
Understanding WCF Vocabulary����������������������������������������������������������������������������������� 270
Creating and Consuming a WCF Service���������������������������������������������������������������������� 271
Creating the Service��������������������������������������������������������������������������������������������������������������������������� 271
Hosting the Service���������������������������������������������������������������������������������������������������������������������������� 276
Consuming the Service����������������������������������������������������������������������������������������������������������������������� 279
Testing the Host and Client����������������������������������������������������������������������������������������������������������������� 282

xi
■ Contents

Hosting a WCF Service in IIS��������������������������������������������������������������������������������������������������������������� 284

Understanding the Role of XML in WCF Services��������������������������������������������������������� 287


Using XmlSerializer Instead of DataContractSerializer����������������������������������������������������������������������� 288

Understanding REST Services�������������������������������������������������������������������������������������� 289


Creating a REST Service Using WCF����������������������������������������������������������������������������� 290
Creating a Client That Consumes the EmployeeManager REST Service��������������������������������������������� 294

Creating a REST Service Using Web API����������������������������������������������������������������������� 298


Creating a Client That Consumes the EmployeeManager Web API Service���������������������������������������� 301
Using XmlSerializer Instead of DataContractSerializer����������������������������������������������������������������������� 303

Summary���������������������������������������������������������������������������������������������������������������������� 304

■Chapter 11: XML in SQL Server�������������������������������������������������������������������������� 305
Using XML Extensions to the SELECT Statement��������������������������������������������������������� 305
The FOR XML Clause�������������������������������������������������������������������������������������������������������������������������� 305

Using OPENXML������������������������������������������������������������������������������������������������������������ 313


Using SQLXML Features����������������������������������������������������������������������������������������������� 315
The SQLXML Managed Classes���������������������������������������������������������������������������������������������������������� 315

The XML Data Type������������������������������������������������������������������������������������������������������� 328


Creating a Table with an XML Column������������������������������������������������������������������������������������������������ 329
Inserting, Modifying, and Deleting XML Data�������������������������������������������������������������������������������������� 329
Methods of the XML Data Type����������������������������������������������������������������������������������������������������������� 330
XML Data Modification Language (XML DML)������������������������������������������������������������������������������������� 332
XQuery Support in the XML Data Type������������������������������������������������������������������������������������������������ 333

Summary���������������������������������������������������������������������������������������������������������������������� 333

■Chapter 12: XML in .NET Framework����������������������������������������������������������������� 335
Using XAML to Define the WPF User Interface������������������������������������������������������������� 335
Displaying XML Data in a WPF Application������������������������������������������������������������������� 340
Using XML in ASP.NET�������������������������������������������������������������������������������������������������� 342
XML and ASP.NET�������������������������������������������������������������������������������������������������������������������������������� 343
The XML Data Source Control������������������������������������������������������������������������������������������������������������� 351

xii
■ Contents

Working with Site Maps����������������������������������������������������������������������������������������������� 359


Using a SiteMapPath Control�������������������������������������������������������������������������������������������������������������� 361
Using a SiteMapDataSource Control��������������������������������������������������������������������������������������������������� 362

Using the XML Control�������������������������������������������������������������������������������������������������� 363


Using the .NET Framework Configuration System������������������������������������������������������� 365
Structure of the web.config File��������������������������������������������������������������������������������������������������������� 367
Web.config Inheritance����������������������������������������������������������������������������������������������������������������������� 367

Using Web.config for Common Configuration Tasks����������������������������������������������������� 367


Storing and Retrieving Application Configuration Settings����������������������������������������������������������������� 368
Storing and Retrieving Database Connection Strings������������������������������������������������������������������������� 369
Using Forms Authentication��������������������������������������������������������������������������������������������������������������� 371
Configuring Session State������������������������������������������������������������������������������������������������������������������ 374
Displaying Custom Error Pages���������������������������������������������������������������������������������������������������������� 376

Documenting Code with XML Comments��������������������������������������������������������������������� 378


Creating a Class Library��������������������������������������������������������������������������������������������������������������������� 378
Using Sandcastle Help File Builder to Generate Help Files����������������������������������������������������������������� 383

Summary���������������������������������������������������������������������������������������������������������������������� 385

■Chapter 13: Working with LINQ to XML������������������������������������������������������������� 387
Overview of LINQ���������������������������������������������������������������������������������������������������������� 387
Working with LINQ Queries����������������������������������������������������������������������������������������������������������������� 388

Classic XML Technologies vs. LINQ to XML������������������������������������������������������������������ 393


Working with XML Fragments������������������������������������������������������������������������������������������������������������ 393
Visual Construction of XML Trees������������������������������������������������������������������������������������������������������� 394
Ease in Namespace Handling������������������������������������������������������������������������������������������������������������� 394
Renaming XML Nodes������������������������������������������������������������������������������������������������������������������������ 394
Static Methods to Load XML��������������������������������������������������������������������������������������������������������������� 394
Whitespace Handling�������������������������������������������������������������������������������������������������������������������������� 394
XML Transformation���������������������������������������������������������������������������������������������������������������������������� 394
When to Use LINQ to XML������������������������������������������������������������������������������������������������������������������� 394
LINQ to XML Class Hierarchy�������������������������������������������������������������������������������������������������������������� 395

xiii
■ Contents

Opening an Existing XML Document for Parsing���������������������������������������������������������� 395


Navigating Through an XML Tree�������������������������������������������������������������������������������������������������������� 397

Looking for Specific Elements and Attributes�������������������������������������������������������������� 399


Retrieving Specific Elements Using the Descendants() Method��������������������������������������������������������� 399
Searching on the Basis of Attribute Values����������������������������������������������������������������������������������������� 400

Modifying XML Data����������������������������������������������������������������������������������������������������� 402


Loading the XML Document���������������������������������������������������������������������������������������������������������������� 403
Navigating Between Various Nodes���������������������������������������������������������������������������������������������������� 403
Adding New Content��������������������������������������������������������������������������������������������������������������������������� 404
Modifying Existing Content����������������������������������������������������������������������������������������������������������������� 405
Deleting Existing Content������������������������������������������������������������������������������������������������������������������� 405
Saving the Modified XML Tree to a File���������������������������������������������������������������������������������������������� 406
Displaying Employee Details�������������������������������������������������������������������������������������������������������������� 406
Events of the XElement Class������������������������������������������������������������������������������������������������������������� 407

Dealing with Whitespace���������������������������������������������������������������������������������������������� 408


Dealing with Namespaces�������������������������������������������������������������������������������������������� 411
Specifying Namespaces While Constructing Elements���������������������������������������������������������������������� 412

Validating XML Documents������������������������������������������������������������������������������������������ 413


Transforming XML Trees����������������������������������������������������������������������������������������������� 415
Changing the Shape of an XML Tree��������������������������������������������������������������������������������������������������� 416
Projecting a New Type������������������������������������������������������������������������������������������������������������������������ 418

Summary���������������������������������������������������������������������������������������������������������������������� 419

■Appendix A: Creating a Custom XmlReader and XmlWriter������������������������������ 421
Creating a Custom XmlReader������������������������������������������������������������������������������������� 421
Inheriting from XmlReader����������������������������������������������������������������������������������������������������������������� 422
Creating the TableReader Class���������������������������������������������������������������������������������������������������������� 423
Using the TableReader Class�������������������������������������������������������������������������������������������������������������� 431

xiv
■ Contents

Creating a Custom XmlWriter��������������������������������������������������������������������������������������� 433


Inheriting from XmlWriter������������������������������������������������������������������������������������������������������������������� 434
Creating the RssWriter Class�������������������������������������������������������������������������������������������������������������� 435
Using the RssWriter Class������������������������������������������������������������������������������������������������������������������ 441

Summary���������������������������������������������������������������������������������������������������������������������� 442

■Appendix B: Resources�������������������������������������������������������������������������������������� 443
W3C Web Site for XML Specifications�������������������������������������������������������������������������� 443
W3C Web Site for XML Schema Specifications������������������������������������������������������������ 443
W3C Web Site for XPath-Related Information�������������������������������������������������������������� 443
W3C Web Site for XSL-Related Information������������������������������������������������������������������ 443
W3C Web Site for SOAP Specifications������������������������������������������������������������������������ 443
System.Xml Reference������������������������������������������������������������������������������������������������� 443
.NET/ASP.NET/WCF/Web API����������������������������������������������������������������������������������������� 444
Wikipedia—XML Section��������������������������������������������������������������������������������������������� 444
Author’s Web Site on .NET and Web Development������������������������������������������������������� 444
XML Notepad—XML Editor������������������������������������������������������������������������������������������ 444
Sandcastle Help File Builder���������������������������������������������������������������������������������������� 444
SQLXML Programming������������������������������������������������������������������������������������������������� 444

Index��������������������������������������������������������������������������������������������������������������������� 445

xv
About the Author

Bipin Joshi is a software consultant, trainer, author, and yoga mentor who writes about seemingly unrelated
topics: software development and yoga! He conducts online training courses to help developers learn
ASP.NET and web technologies better and faster. Currently his focus is ASP.NET, ASP.NET Core, C#,
JavaScript frameworks, and design/architectural patterns. More details about his training courses are
available at http://www.binaryintellect.com.
Bipin has been programming since 1995 and has worked with the .NET Framework since its inception.
He is a published author and has authored or co-authored more than 10 books and numerous articles on
.NET technologies. He regularly writes about ASP.NET and other cutting-edge web technologies on his web
site at http://www.binaryintellect.net. Bipin is a Microsoft Most Valuable Professional (MVP) and a
former Microsoft Certified Trainer (MCT).
Having embraced the yoga way of life, he enjoys the intoxicating presence of God and writes about yoga
on his web site at http://www.bipinjoshi.org. Bipin has also penned a few books on yoga and teaches
yoga and meditation to selected individuals. He can be reached through his web sites.

xvii
About the Technical Reviewer

Michael Thomas has worked in software development for more than


20 years as an individual contributor, team lead, program manager, and
vice president of engineering. Michael has more than 10 years of
experience working with mobile devices. His current focus is in the
medical sector, using mobile devices to accelerate information transfer
between patients and health care providers.

xix
Introduction

The Internet has brought a huge difference in the way we develop and use software applications.
Applications have become more complex and distributed, connecting heterogeneous systems.
With such a radical change, the role of XML is highly significant. XML has already established itself as
a standard way of data encoding and transfer. In spite of the popularity of formats such as JSON (JavaScript
Object Notation), XML is still being used in a wide range of applications, including enterprise applications.
XML comes with a family of technologies such as XSLT, XPath, and XSD, that provide a fuller support for
transforming, querying, and validating the underlying data.
No wonder that Microsoft’s .NET Framework provides such a strong support for XML. Data access, raw
parsing, serialization, configuration, code documentation, and services are some of the examples where the
.NET Framework harnesses the power and flexibility of XML.
The .NET Framework comes with a plethora of classes that allow you to work with XML data. This book
demystifies XML and allied technologies. Reading and writing XML data, using DOM, ADO.NET integration
with XML, SQL Server XML features, applying XSLT style sheets, SOAP, use of XML in services (ASMX/
WCF/Web API), and configuration systems are some of the topics that this book explores in detail. Neat
and concise examples scattered throughout the book will help you understand the practical use of the topic
under consideration. The book can also act as a handy reference when developers go on the job.

Who Is This Book For?


This book is for developers who are familiar with the .NET Framework and want to dive deep into the XML
features of .NET. This book will not teach you XML manipulation using non-Microsoft tools. All the examples
in this book are presented in C#, and hence working knowledge of C# is assumed. In some chapters,
familiarity with LINQ, ADO.NET, and SQL Server is necessary, although I have provided a brief overview
along with the respective topics.

Software Required
In order to work with the examples presented in this book, you need the following software:
• Visual Studio 2017: I used the Professional Edition of the product but for most of the
examples you can also use the Community Edition.
• .NET Framework 4.7 and C# 7: I used .NET Framework 4.7 to build the examples
discussed in this book. The examples and code fragments are written using C# 7.
• SQL Server with Northwind sample database: In the examples that rely on a
database, I used SQL Server 2012 Developer Edition. You may also use some later
version of the product if you so wish. Throughout the book we use data from the
Northwind sample database. So, you need it ready in the SQL Server. You can
download the required scripts from Microsoft’s official web site.

xxi
■ Introduction

• SQLXML 4.0 SP1: In the examples that discuss SQLXML programming, you need
SQLXML 4.0 SP1 installed on your machine. It can be downloaded from Microsoft’s
official web site.
• Sandcastle Help File Builder (SHFB): In the examples that discuss XML code
commenting, you need SHFB to generate the documentation. You can download it
from its GitHub page.
• Browser: In the examples that require a web browser, I used Firefox. But any other
browser should also work.

Structure of This Book


The book is divided into 13 chapters and two appendices.
Chapters 1 to 4 talk about navigating, reading, and writing XML documents by using classes from
the System.Xml namespace. In these chapters, you learn to use classes such as XmlDocument, XmlReader,
XmlWriter, and XPathNavigator.
Manipulating XML data is just one part of the story. Often you need to validate and transform it so
that it becomes acceptable to your system. Chapters 5 and 6 deal with XML document validation and XSLT
transformations, respectively.
The .NET Framework technologies themselves use XML in many ways. This is often under the hood,
but for any XML developer, knowing where this occurs is essential. To that end, Chapters 7 to 10 cover topics
such as ADO.NET integration with XML, XML serialization, and ASMX/WCF/Web API services.
Microsoft has not limited the use of XML only to areas such as ADO.NET, serialization, and services.
SQL Server incorporates many XML-related features. These features are discussed in Chapter 11. Although
this topic isn’t strictly one of the XML features of .NET Framework, many developers will find it useful,
because many real-world projects developed using the .NET Framework use SQL Server as a datastore.
Chapter 12 covers many other areas where the .NET Framework uses XML. Some of them include
XAML, ASP.NET server controls, XML configuration files, and XML comments.
Language Integrated Query (LINQ) includes what is known as LINQ to XML. It can be used to handle
XML data in LINQ-style. Chapter 13 is dedicated to this programming model. Here, you will learn about core
LINQ to XML features, including parsing and loading XML trees the LINQ to XML way and validating and
projecting XML data.
Finally, the two appendices supplement what you learned throughout the book by providing some
more information and resources.

Downloading the Source Code


The complete source code for the book is available for download at the book’s companion web site. Visit
www.apress.com and go to this book’s information page. You can then download the source code from the
Source Code/Downloads section.

Contacting the Author


You can reach me via my web site at http://www.binaryintellect.net. You can also follow me on various
social networking sites (visit my web site for the links).

xxii
CHAPTER 1

Introducing XML and the .NET


Framework

Over the years XML has emerged as one of the most important standards for data representation and
transportation. No wonder that Microsoft has embraced it fully in the .NET Framework. This chapter
provides an overview of what XML is and how it is related to the .NET Framework. Many of the topics
discussed in this chapter might be already familiar to you. Nevertheless, I will cover them briefly here so as
to form a common platform for further chapters. Specifically, this chapter covers the following:
• Features and benefits of XML
• Rules of XML grammar
• Brief introduction to allied technologies such as DTD, XML Schema, parsers, XSLT,
and XPath
• Overview of the .NET Framework
• Use of XML in the .NET Framework
• Introduction to Visual Studio
If you find these concepts highly familiar, you may want to skip ahead to Chapter 2.

What Is XML?
XML stands for Extensible Markup Language and is a markup language used to describe data. It offers a
standardized way to represent textual data. Often the XML data is also referred to as an XML document.
The XML data doesn’t perform anything on its own; to process that data, you need to use a piece of software
called a parser. Unlike Hypertext Markup Language (HTML), which focuses on how to present data, XML
focuses on how to represent data. XML consists of user-defined tags, which means you are free to define and
use your own tags in an XML document.
XML was approved as a recommendation by the World Wide Web Consortium (W3C) in February 1998.
Naturally, this very fact contributed a lot to such a wide acceptance and support for XML in the software
industry.
Now that you have brief idea about XML, let’s see a simple XML document, as illustrated in Listing 1-1.

© Bipin Joshi 2017 1


B. Joshi, Beginning XML with C# 7, https://doi.org/10.1007/978-1-4842-3105-0_1
Chapter 1 ■ Introducing XML and the .NET Framework

Listing 1-1. A Simple XML Document


<?xml version="1.0" encoding="utf-8" ?>
<customers>
  <customer ID="C001">
    <name>Nancy Davolio</name>
    <email>nancy@localhost</email>
    <comments>
      <![CDATA[Regular customer since 1995]]>
    </comments>
  </customer>
  <customer ID="C002">
    <name>Steven Buchanan</name>
    <email>steven@localhost</email>
    <comments>
      <![CDATA[New customer interested in multiple services]]>
    </comments>
  </customer>
</customers>

Many rules govern the creation of such XML documents. But we will save them for later discussion.

Benefits of XML
Why did XML become so popular? Well, this question has many answers, and I will present some of the
important ones in this section.

XML Is an Industry Standard


As you learned previously, XML is a W3C recommendation. This means it is an industry standard governed
by a vendor-independent body. History shows that vendor-specific proprietary standards don’t get massive
acceptance in the software industry. This non-acceptance affects overall cross-platform data sharing and
integration. Being an industry standard has helped XML gain huge acceptance.

XML Is Self-Describing
XML documents are self-describing. Because of markup tags, they are more readable than, say, comma-
separated values (CSV) files.

XML Is Extensible
Markup languages such as HTML have a fixed set of tags and attributes—you cannot add your own tags.
XML, on the other hand, allows you to define your own markup tags.

XML Can Be Processed Easily


Traditionally, the CSV format was a common way to represent and transport data. However, to process such
data, you need to know the exact location of the commas (,) or any other delimiter used. This makes reading
and writing the document difficult. The problem becomes severe when you are dealing with a number of
altogether different and unknown CSV files.
2
Chapter 1 ■ Introducing XML and the .NET Framework

As I said earlier, XML documents can be processed by a piece of software called a parser. Because XML
documents use markup tags, a parser can read them easily. Parsers are discussed in more detail later in this
chapter.

XML Can Be Used to Easily Exchange Data


Integrating cross-platform and cross-vendor applications is always difficult and challenging. Exchanging
data in heterogeneous systems is a key problem in such applications. Using XML as a data-exchange format
makes your life easy. XML is an industry standard, so it has massive support, and almost all vendors support
it in one way or another.

XML Can Be Used to Easily Share Data


The fact that XML is nothing but textual data ensures that it can be shared among heterogeneous systems.
For example, how can the data generated by a Windows Forms application running on a Windows machine
be accessible in a Java application running on a Unix box? XML is the answer.

XML Can Be Used to Create Specialized Vocabularies


As you already know, XML is an extensible standard. By using XML as a base, you can create your own
vocabularies. Wireless Application Protocol (WAP), Wireless Markup Language (WML), and Simple Object
Access Protocol (SOAP) are some examples of specialized XML vocabularies.

XML-Driven Applications
Now that you know the features and benefits of XML, let’s see what all these benefits mean to modern
software systems.
Figure 1-1 shows a traditional web-based application. The application consists of ASP.NET pages
hosted on a web server. The client, in the form of a web browser, requests various web pages. On receiving
the requests, the web server processes them and sends the response in the form of HTML content. This
architecture sounds good at first glance, but suffers from several shortcomings:
• It considers only web browsers as clients.
• The response from the web server is always in HTML. That means a desktop-based
application may not render this response at all.
• The data and presentation logic are tightly coupled. If we want to change the
presentation of the same data, we need to make considerable changes.
• Tomorrow, if some other application wants to consume the same data, it cannot be
shared easily.

3
Chapter 1 ■ Introducing XML and the .NET Framework

Figure 1-1. Classic architecture for developing applications

Now, let’s see how XML can come to the rescue in such situations.

■■Note For the sake of easy understanding the example discussed here is deliberately kept very simple and
straightforward. In a more realistic case there could be one or more services involved that return the XML data.
The applications then consume those services as and when required. You will learn how XML and services are
related in later chapters.

Have a look at Figure 1-2, where there are multiple types of clients. One is a web browser, and the other
is a desktop application. Both send requests to the server along with XML data (if any). The server processes
the requests and sends back the data in XML format. The web browser applies a style sheet (discussed later)
to the XML data to transform it into HTML markup. The desktop application, on the other hand, parses the
data by using an XML parser (discussed later) and displays it in a grid. Much more flexible than the previous
architecture, isn’t it? The advantages of the new architecture are as follows:
• The application has multiple types of clients. It is not tied only to web browsers.
• There is loose coupling between the client and the processing logic.
• New types of clients can be added at any time without changing the processing logic
on the server.
• The data and the presentation logic are neatly separated from each other. Web
clients have one set of presentation logic, whereas desktop applications have their
own presentation logic.
• Data sharing becomes easy, because the outputted data is in XML format.

4
Chapter 1 ■ Introducing XML and the .NET Framework

Figure 1-2. XML-driven architecture

Rules of XML Grammar


In the “What Is XML?” section, you saw one example of an XML document. However, I didn’t talk about any
of the rules that you need to follow while creating it. It’s time now to discuss those rules of XML grammar. If
you have worked with HTML, you will find that the rules of XML grammar are stricter than the HTML ones.
However, this strictness is not a bad thing, because these rules help ensure that there are no errors while we
parse, render, or exchange data.
Before I present the rules in detail, you need to familiarize yourself with the various parts of an XML
document. Observe Figure 1-3 carefully.

Figure 1-3. Parts of a typical XML document

5
Chapter 1 ■ Introducing XML and the .NET Framework

Line 1 is called a processing instruction. A processing instruction is intended to supply some information
to the application that is processing the XML document. Processing instructions are enclosed in a pair of
<? and ?>. The xml processing instruction in Figure 1-3 has two attributes: version and encoding. The W3C
recommendations for XML hold version 1.0, hence the version attribute is set to 1.0.

■■Note You may come across XML 1.1 while reading more about XML specifications. There are minor
differences between XML 1.0 and XML 1.1. However, considering the wide acceptance for version 1.0 most of
the XML documents prefer to mention that version. When you add a new XML file using Visual Studio it has its
version attribute set to 1.0. You can find more details about these differences on the official web site of W3C.

Line 2 represents a comment. A comment can appear anywhere in an XML document after the xml
processing instruction and can span multiple lines.
Line 3 contains the document element of the XML document. An XML document has one and only one
document element. XML documents are like an inverted tree, and the document element is positioned at
the root. Hence, the document element is also called a root element. Each element (whether or not it is the
document element) consists of a start tag and an end tag. The start tag is <customers>, and the end tag is
</customers>.
It is worthwhile to point out the difference between three terms: element, node, and tag. When you say
element, you are essentially talking about the start tag and the end tag of that element together. When you say
tag, you are talking about either the start tag or end tag of the element, depending on the context. When you
say node, you are referring to an element and all its inner content, including child elements and text.
Inside the <customers> element, you have two <customer> nodes. The <customer> element has one
attribute called ID. The attribute value is enclosed in double quotes. The <customer> element has three
child elements: <name>, <email>, and <comments>. The text values inside elements, such as <name> and
<email>, are often called text nodes. Sometimes, the text content that you want to put inside a node may
contain special characters such as < and >. To represent such content, you use a character data (CDATA)
section. Whatever you put inside the CDATA section is treated as a literal string. The <comments> tag shown in
Figure 1-3 illustrates the use of a CDATA section.
Now that you have this background, you’re ready to look at the basic rules of XML grammar. Any XML
document that conforms to the rules mentioned next is called a well-formed document.

Markup Is Case Sensitive


Just like some programming languages, such as C#, XML markup is case sensitive. That means <customer>,
<Customer>, and <CUSTOMER> all are treated as different tags.

A Document Must Have One and Only One Root Element


An XML document must have one and only one root element. In the preceding example, the <customers>
element is the root element. Note that it is mandatory for XML documents to have a root element.

A Start Tag Must Have an End Tag


Every start tag must have a corresponding end tag. In HTML, this rule is not strictly followed—for example,
tags such as <br> (line break), <hr> (horizontal rule), and <img> (image) are often used with no end tag at all.
In XML, that would not be well formed. The end tag for elements that do not contain any child elements or

6
Chapter 1 ■ Introducing XML and the .NET Framework

text can be written by using shorter notation. For example, assuming that the <customer> tag doesn’t contain
any child elements, you could have written it as <customer ID="C001"/>.

Start and End Tags Must Be Properly Nested


In HTML, the rule about properly nesting tags is not followed strictly. For example, the following markup
shows up in the browser correctly:

<B><I>Hello World</B></I>

This, however, is illegal in XML, where the nesting of start and end tags must be proper. The correct
representation of the preceding markup in XML would be as follows:

<B><I>Hello World</I></B>

Attribute Values Must Be Enclosed in Quotes


In HTML, you may or may not enclose the attribute values. For example, the following is valid markup in
HTML:

<IMG SRC=myphoto.jpg>

However, this is illegal in XML. All attribute values must be enclosed in quotes. Thus the accepted XML
representation of the preceding markup would be as follows:

<IMG SRC="myphoto.jpg" />

DTD and XML Schema


Creating well-formed XML documents is one part of the story. The other part is whether these documents
adhere to an agreed structure, or Schema. That is where Document Type Definition (DTD) and XML
Schemas come into the picture.
DTDs and XML Schemas allow you to convey the structure of your XML document to others. For
example, if I tell you to create an XML file, what structure will you follow? What is the guarantee that the
structure that you create is the one that I have in mind? The problem is solved if I give you a DTD or an XML
Schema for the document. Then, you have the exact idea as to how the document should look and what its
elements, attributes, and nesting are.
The XML documents that conform to some DTD or XML Schema are called valid documents. Note
that an XML document can be well formed, but it may not be valid if it doesn’t have an associated DTD or
Schema.
DTDs are an older way to validate XML documents. Nowadays, XML Schema—also called XML Schema
Definition or XSD—is more commonly used to validate XML documents because of the advantages it offers.
You will learn about the advantages of XSD over DTD in Chapter 5. Throughout our discussion, when I talk
about validating XML documents, I will be referring to XML Schemas.

7
Chapter 1 ■ Introducing XML and the .NET Framework

Parsing XML Documents


XML data by itself cannot do anything; you need to process that data to do something meaningful. As I
have said, the software that processes XML documents is called a parser (or XML processor). XML parsers
allow you read, write, and manipulate XML documents. XML parsers can be classified in three categories
depending on how they process XML documents:
• DOM-based parsers (DOM stands for Document Object Model)
• SAX-based parsers (SAX stands for Simple API for XML)
• Pull-model parsers
DOM-based parsers are based on the W3C’s DOM recommendations and are possibly the most
common and popular. They look at your XML document as an inverted tree structure. Thus, our XML
document shown in Figure 1-3 will be looked at by a DOM parser as shown in Figure 1-4.

Figure 1-4. The DOM representation of an XML document

DOM-based parsers are read-write parsers, which means you can read as well as write to the XML
document. They allow random access to any particular node of the XML document, and therefore, they need
to load the entire XML document in memory. This also implies that the memory footprint of DOM-based
parsers is large. DOM-based parsers are also called tree-based parsers for obvious reasons.
SAX-based parsers do not read the entire XML document into memory at once. They essentially scan
the document serially from top to bottom. When they encounter various parts of the document, they raise
events, and you can handle these events to read the document. SAX parsers are read-only parsers, which
means you cannot use them to modify an XML document. They are useful when you want to read huge XML
documents and loading such documents into memory is not advisable. These types of parsers are also called
event-based parsers.

8
Chapter 1 ■ Introducing XML and the .NET Framework

Pull-model parsers iterate through an XML document sequentially. They use the iterator design pattern
to create an iterator. The iterator sequentially visits various parts of a document such as elements and
attributes. You can inspect the type of the item under consideration to determine whether it’s a start tag, end
tag, or a text node. You can also read its attributes. Moreover, you can move the iterator to the next item. The
.NET Framework’s XmlReader falls in this category.
Parsers can also be classified as validating and nonvalidating. Validating parsers can validate an XML
document against a DTD or XML Schema as they parse the document. On the other hand, nonvalidating
parsers lack this ability.

■■Note LINQ to XML offers an in-memory way of reading and writing XML documents. You will learn
more about LINQ to XML later in this chapter. Chapter 13 covers the LINQ features as applicable to XML data
manipulation in fuller details.

XSLT
XML solves the problem of data representation and exchange. However, often we need to convert this XML
data into a format understood by the target application. For example, if your target is a web browser, the
XML data must be converted to HTML before displaying in the browser.
Another example is that of business-to-business (B2B) applications. Let’s say that application A
captures order data from the end user and represents it in some XML format. This data then needs to be sent
to application B that belongs to some other business. It is quite possible that the XML format as generated by
application A is different from that required by application B. In such cases, you need to convert the source
XML data to a format acceptable to the target system. In short, in real-world scenarios you need to transform
XML data from one form to another.
That is where XSLT comes in handy. XSLT stands for Extensible Style Sheet Language Transformations
and allows you to transform XML documents from one form into another. Figure 1-5 shows how this
transformation happens.

9
Chapter 1 ■ Introducing XML and the .NET Framework

Figure 1-5. XML transformation using XSLT

XPath
Searching for and locating certain elements within an XML document is a fairly common task. XPath is
an expression language that allows you to navigate through elements and attributes in an XML document.
XPath consists of various XPath expressions and functions that you can use to look for and select elements
and attributes matching certain patterns. XPath is also a W3C recommendation. Figure 1-6 shows an
example of how XPath works.

10
Exploring the Variety of Random
Documents with Different Content
kuultuaan sinusta tällaisia asioita. Sinä olet sellainen poika, jota me
kaikki kunnioitamme ja josta me paljon pidämme. Minä luulen
myöskin huomanneeni, että toveriesi tunteet sinua kohtaan ovat
samanlaisia. Me olemme siitä ymmärtäneet, että sinun on ehkä
vaikeampi kuin muiden tunnustaa tehneesi halpamaista petosta. Kun
sinä nyt yrität valheella päästä eroon asiasta, olet sinä väärässä
luulossa, jos uskot valheen itseäsi paremmin auttavan kuin suoran,
rehellisen tunnustuksen. Me olemme päättäneet antaa sinulle
anteeksi tämän väärän luulon. Me toivomme, että sinä annat sille
oikean arvon, tajuat, että meidän hyvä mielipiteemme sinusta
velvoittaa sinua.

Antti Bech seisoi, taistellen itkua vastaan, rehtorin puhuessa. Kun


puhe oli loppunut, nieli hän itkunsa suurella ponnistuksella ja sanoi:

— Minä en ole tehnyt petosta.

Rehtori tarkasti häntä tutkivalla katseellaan.

— Etkö sinä itse ole tunnustanut ottaneesi vihkosi lauantaina


laatikosta — ja kirjoittaneesi laskut vihkoon laulutunnilla.

— O — olen, mutta…

— So, sanoi rehtori, kumarsi hiukan Svenningsenille ja meni.

Antti Bech pikemmin putosi kuin istui tuolilleen; hän laski päänsä
käsivarsilleen pöydälle ja voihki.

Svenningsen seisoi selin luokkaan ja katseli ulos akkunasta. Pari


kertaa hän kääntyi katsoen Anttiin päin, joka nyyhki ääneen. Pojat
istuivat hiljaa.
Lopulta Svenningsen sanoi: — Ellet sinä voi hillitä itseäsi, Antti
Bech, niin mene ulos, kunnes tyynnyt.

Antti Bech meni.

Vielä kesti hetkisen, ennenkuin opettaja Svenningsen antoi jatkaa


käännöstä.

Antti Bech ei tullut takaisin; eikä hän seuraavalla tunnillakaan ollut


paikallaan.

Hän oli mennyt kotiin.

*****

Mikko Tiukkatuuli astui kotiin päin. Hänestä tuntui kuin eivät jalat
kannattaisi häntä; polvet notkuivat ja letkahtelivat.

Päivällispöydässä hän kertoi ykkösestään kotilaskuissa. Ruoka


tarttui kurkkuun; hän nieli ja nieli.

Ruualta hän meni huoneeseensa. Täällä hän heittäytyi sänkyynsä


— vatsalleen, haudaten päänsä tyynyyn. Hänellä oli kauhea halu
saada itkeä, mutta ei mitenkään voinut. Rinnan alla tuska pakotti —
ontto, kiertävä tuska.

Näin hän makasi tunnin ajan liikahtamatta. Sitten hän nousi


vitkaan. Hän katsahti ympärilleen huoneessa, istui sängyn laidalle
antaen jalkojensa veltosti roikkua. Taaskin kului pitkän pitkä hetki.

Sitten hän nousi, meni vitkaan alas portaita, otti lakkinsa eteisestä.
Hän pysähtyi konttoorin oven taakse ja kuunteli. Isä oli sisällä. Hän
tarttui ovenripaan, pysähtyi, päästi irti taas ja meni ulos kadulle.
Hiljakseen hän astui katua; ajoneuvot tärskyivät ja kolisivat,
ihmiset kulkivat hänen ohitsensa; hän ei näyttänyt niitä näkevän eikä
kuulevan, hän kuvitteli olevansa kosteassa jääpuvussa.

Hän tuli aivan koulun ovelle saakka. Täällä hän pysähtyi ja pyyhki
otsaansa nenäliinalla; se tuli likomäräksi tuskanhiestä.

Kun hän tarttui raskaaseen ovenripaan, teki mieli pysähtyä ja


miettiä; mutta hän riensi avaamaan. Hän kulki kaikkien autioiden
käytävien lävitse, kunnes pysähtyi rehtorin kanslian oven taakse.
Hän koputti hiljaa.

Kukaan ei vastannut.

Sitten hän koputti kovemmin. Ei kukaan vieläkään vastannut.

Kanslian oven vieressä oli rehtorin yksityinen sisäänkäytävä. Hän


tavotti kelloa; mutta nyt hän mietti. Hyvin kauan.

Silloin kuului askelia sisältä eteisestä, samassa hän vetäsi


kellonnauhasta.

Rehtorin rouva avasi oven.

— Saisinko vähän puhutella rehtoria?

— Kyllä, heti!

Rehtorin rouva vei hänet eteisestä erään sisäoven kautta


kansliaan.

— Olkaa hyvä, istukaa, kyllä hän pian tulee.

Hän nosti korkeaselkäisen nahkatuolin pojalle ja meni.


Mikko Tiukkatuuli istui kovalle tuolille.

Rehtorin kansliahuone oli pitkä ja kapea, akkuna toisessa päässä.


Seiniä peittivät hyllyt, niin, seinät olivat pelkkänä hyllynä, kirjat
seisoivat tiheissä rivissä katosta lattiaan asti.

Mikko Tiukkatuuli istui korkeaselkäisessä tuolissa suorana, melkein


pystyssä, sillä selkänoja oli aivan kohtisuora. Hänen varpaansa
ulottuivat juuri lattiaan. Hän katseli ympärilleen, tuijottain kirjoihin;
vähä vähältä alkoi hänestä tuntua siltä, kuin seinät lähestyisivät
toisiaan, lähemmäksi yhä lähemmäksi — tahtoen likistää hänet
väliinsä ja painaa nuo kankeat ja kiristetyt kirjain selät häneen — —

Hän liukui alas tuolilta. Hän saattoi tuskin seisoa tuskalta, hiipi
ovelle, tarttui avaimeen: ovi oli suljettu.

Ja toinen ovi — se johti eteiseen!

Hän huudahti, kuu ovi äkkiä aukeni eteiseen, Rehtori tuli.

Hänellä oli sama kotitakki, jonka Mikko Tiukkatuuli oli nähnyt


ollessaan laiskanläksyllä.

— No, Mikkoseni, sinä tahdoit puhutella minua.

— Niin.

Rehtori seisoi hänen edessään katsellen häntä ja odottaen. Mutta


poika ei voinut sanoa muuta kuin "niin".

Mikko Tiukkatuuli tuijotti jäykästi rehtoriin, tuijotti ja tuijotti, aivan


sanatonna.
Rehtori sanoi viimein:

— No, mikä oli asia? Hän meni suuren työpöytänsä luo akkunan
eteen; rehtori istui ja tarjosi Mikko Tiukkatuulelle tuolia edessään.

— Se oli — se oli niin, — että minä olenkin petokseen syypää.

— Oletko sinä harjoittanut petosta?

— Olen, eikä Antti Bech.

— Selitä, poikaseni!

Mikko kertoi lauantai-aamuisesta tapauksesta, että Antti oli


laskenut irtonaiselle paperille ja pannut sen vihkoonsa, kuinka hän
oli kaatanut sille mustetta ja kirjoittanut sijaan uuden, Simo Selmerin
laskujen mukaan, joiden hän oli luullut olevan oikein, niinkuin aina
ennenkin.

— Antti Bech oli siis laskenut esimerkit?

— Oli, irtonaiselle lapulle. Hän sanoi edellisenä päivänä, ettei hän


ennättänyt kirjoittaa niitä vihkoonsa, — ainoastaan esimerkit olivat
vihossa.

Rehtori istui kauan ääneti katsellen ulos akkunasta Lopulta hän


sanoi:

— Eikö hän huomannut, että se lappu, jonka mukaan hän kirjoitti,


ei ollutkaan hänen, vaan jonkun muun kirjoittama?

— Ei. Minä koetin saada sen niin saman näköiseksi kuin suinkin.
Rehtori oli taas kauan vaiti ja katseli ulos. Sitten hän kääntyi
vitkaan Mikko Tiukkatuulen puoleen ja sanoi:

— Sinä teit siis petoksen?

— Niin.

— Mutta — mutta hyvä Mikko, sinullahan on opettaja Winther…

Mikko Tiukkatuuli tuijotti jäykällä katseella rehtori Holstiin ja ravisti


päätään.

— Eikö hän auta sinua? Otathan sinä tuntia hänen luonaan?

— Minä en ota tuntia Wintherillä.

— Kuka sinua sitten opettaa? Minä muistelen sinun sanoneen…

— Ei minua kukaan opeta,

— Mutta kirjoitinhan minä isällesi…

— Minä en antanut kirjettä isälle.

— Etkö sinä antanutkaan minun kirjettäni isällesi?

Mikko Tiukkatuuli istui niinkuin ennenkin tuijottaen — ja ravisti


päätään. Rehtori Holst katsoi tutkivasti häneen, sitten akkanaan ja
taas Mikko Tiukkatuuleen:

— Mutta kuinka sinä tiesit kertoa ottavasi yksityistuntia


laskennossa, josta minä olin kirjoittanut?
Mikko Tiukkatuulen huulet vapisivat, yhä pahemmin ja pahemmin
— tuijottavat silmät täyttyivät vähitellen kyynelillä — hän rykäsi ja
sai viimein ääntä:

— Minä mursin kirjeen ja luin sen.

Rehtori Holst nousi tuoliltaan ja käveli lattialla edes takaisin.


Kauan. Sitten hän pysähtyi Mikko Tiukkatuulen eteen ja sanoi syvästi
ja tutkivasti katsoen häneen:

— Semmoinenko sinä oletkin?

— E — en, en! Minä en — ole semmoinen! huusi Mikko


Tiukkatuuli, ja nyt tuli suuri itku, joka oli vaivannut ja painanut häntä
aamusta aikain.

Rehtori Holst antoi hänen itkeä pitkän aikaa. Kun kovin nyyhkytys
oli asettunut, kysyi hän:

— Sanoppas minulle, Mikko, tietääkö Antti Bech tästä?

— Ei — mutta — minä — menen sanomaan hänelle nyt.

— Nyt — niin. On parasta, että lähdet nyt jo heti!

Mikko Tiukkatuuli otti lakkinsa ja meni. Hän oli jo melkein ovesta


ulkona, mutta palasi takaisin ja kumarsi rehtorille. Hän oli unohtanut
sen.

Hän meni suoraan kaupunginvouti Bechille.

Kun hän nyt vaan saisi sanotuksi kaikki tyyni Antti Bechille — niin
tulkoon sitten koko kurjuus.
Koulusta hänet nyt kaiketikin eroitettaisiin. Ja kotona isä ottaisi
puheeksi konepajan, tai merille lähdön, tai puotipaikan.

Vielä ei hän tahtonut tätä ajatella — olihan sitä aikaa sittenkin,


kun hän ensin oli käynyt Antin luona. Hän riensi. Tie kulki kodin
ohitse; hän juoksi akkunain kohdalla. — — — Puolen tunnin kuluttua
oli kaikki sanottu ja tehty Antti Bechin luona, poikien huoneessa.
Mikko Tiukkatuuli istui Antin sängyn laidalla ja tähysti lakkaamatta
lattiaa. Antti Bech istui pöydällään, heilutellen jalkojaan ja katsellen
ulos.

— Ja kaiken tämän olet sinä tunnustanut suoraan rehtorille?

— Niin. Parasta oli saada sanotuksi kaikki yht'aikaa.

— Nyt saat sinä, Mikko — nuhdesaarnan huomenna.

— Jos minä vaan pääsisin nuhdesaarnalla, niin —!

Pitkä äänettömyys. Viimein Mikko Tiukkatuuli sanoi, hellittämättä


katsettaan lattiasta:

— Oletko sinä sikamaisesti suuttunut minuun, Antti?

— Tökerö, vastasi Antti Bech.

Mikko Tiukkatuuli alkoi soudattaa itseään istuallaan.

— Niin, näetkös, ellet sinä vaan ole minulle vihainen enää!

— Minusta sinä olet ollut suuremmoisesti rehti — mennyt suoraan


rehtorille…
— No, sitten minä olen taas iloinen. Käyköön nyt miten tahansa.
Kun et sinä vaan tahdo ajatella minusta pahaa, — kun olen poissa.

— Lähdetkö sinä jonnekin?

— Eihän minulla ole muuta neuvoa, näetkös. Täytyy koettaa


paeta.

— Pa — paetako?

— Niin. Minä karkaan kotoa; tänä yönä ehkä.

— Oletko sinä hullu!

— Minä en kestä tätä kaikkea. Jos minut nyt ajetaan pois koulusta,
niin joutuu isäni aivan epätoivoon, häpeästä, näetkös. Molemmat, isä
ja äitikin. Heidän pitäisi kuitenkin keksiä minulle jotakin. Ehkä
lähettäisivät jonnekin muualle. Yhtä hyvinhän minä voin mennä itse.
Jo ajoissa. Sillä minä en kestä, en.

— Mutta — minne sinä aijot paeta, poika?

— Vähät siitä! Ainahan tuota jonnekin pääsee piiloutumaan,


kunnes muut ovat unhoittaneet. Minä aijon kävellä johonkin
eteläisempään kaupunkiin. Sieltä lähtee laivoja Amerikaan.

— Sinä joudut kiinni!

— En, kun vaan pysyttelen maaseudulla. Kulen talosta taloon —


kunnes saavun perille.

— Entä rahat?

— Minulla on 20 kruunua omaa rahaa.


— Niillä sinä et pitkälle pääse, poika! Saat vielä nälkää nähdä.

— No, niin. Voihan niinkin käydä. Jos kuoleekin nälkään tunturilla,


— entä sitten — onhan silloin ainakin päässyt pois. Pois kaikesta
tästä.

Mikko Tiukkatuuli puhui itkunsekaisella äänellä ja nousi seisoalleen


lattialle.

— Jos minä olisin poissa huomenna, niin sinä et luonnollisesti


tiedä mitään!

— En tietystikään, mutta…

— Ja ehkä sinä kirjoittaisit minulle. Kun minä vaan lähetän sinulle


osoitteeni. Sinä — sinä olet minun ainoa ystäväni, Antti, tiedätkös.
No, hyvästi nyt!

Antti Bech hyppäsi alas pöydältä.

— Oikeinko sinä tosissasi — aiotkos sinä karata?

— Eihän minulla muutakaan neuvoa ole, tajuathan sen. Minusta


tulee sellainen — sellainen pois potkittu raukka!

— No, sitä minä nyt en usko! sanoi Antti Bech.

— Onhan se sikamaisen rohkea työ, karata. Mutta jos sinä ensin


tunnustaisit kaiken tämän isällesi! Koettaaksesi, miten se häneen
vaikuttaisi!

— Minä — minä en uskalla. Minä — en tosiaankaan uskalla.


Itku valtasi Mikko Tiukkatuulen, Hau puri hampaitaan, estääkseen
sitä tulemasta.

— Hyvästi nyt, Antti! sanoi hän ja riensi ulos ovesta.

Hän meni kotiin päin.

Pakenemisen mahdollisuus oli kytenyt hänen mielessään jo kauan,


kauan aikaa. Ja nyt, puhellessa Antti Bechin kanssa, oli se äkkiä
kypsynyt lujaksi päätökseksi…

Mutta jos tunnustaisit ensin kaikki tyyni isällesi! Ja saisit nähdä


miten se häneen vaikuttaisi!

Niin, kun vaan olisi — olisi rohkeutta!

Hän oli sentään uskaltanut mennä rehtorin luo…!

Mutta isän…!

Ei, hän tunsi itsessään: Hän ei voisi toista kertaa — ja vielä isälle!
Ja äitikin tulisi, — sisaret saisivat tietää!

Nyt hän oli omalla kadulla, näki talon.

Hän pysähtyi äkkiä.

Hänen edellään kulki levollisesti muuan mies, jonka polvet


notkahtelivat omituisesti —: rehtori Holst! Takaapäin jo saattoi
kuvitella miehellä olevan tummat, vakavat kasvot.

Mikko Tiukkatuuli seisoi kuin naulittu paikallaan, vavisten


tuskallisesta pelosta.
— Niin, niin todellakin! Oi Jumala! Rehtori meni hänen kotiinsa!

Hän meni ilmoittamaan isälle!

— Oi — oi! oi — oi! Mikko Tiukkatuuli voihki ehdottomasti


puoliääneen itsekseen. Hän pyörähti ympäri ja kulki vastakkaista
tietä pitkin katuja.

Hän käveli ja käveli. Veri nousi päähän, koko ruumis aivan horjui.

Hän joutui maantielle. Päästyään maaseudulle kappaleen matkaa,


ei hän jaksanut kauemmaksi, vaan istui tien viereen.

Istuminen auttoi hiukan. Mutta vain hetkeksi. Sitten taas valtasi


hänet — tuo kauhea tuska ja epätoivo. Hän istui tuijottaen eteensä
ja ajatteli aina vaan samaa asiaa:

Että hän oli tuollainen, jollaisista joskus kuultiin, hyvien


vanhempien lapsi, joka häpäisi heidät, kotinsa ja itsensä, joka "joutui
hunningolle" — piti lähteä Amerikaan. Yksi niistä, joiden tie usein
päättyy kuritushuoneeseen.

Mikko Tiukkatuuli pani kätensä ristiin ja rukoili Jumalaa.

Mutta eihän Jumala voinut välittää — hänen rukouksestansa nyt!


Nytkö vasta oli aika rukoilla Jumalaa, nyt hädässä ja kurjuudessa?
Silloin, kirjettä polttaessaan olisi hänen pitänyt ajatella Jumalaa. Hän
tunsi olevansa halpamainen ja tuhma Jumalan edessä, luullessaan,
ettei Jumala tajuaisi, kuinka häntä nyt pelko pakoitti — rukoilemaan!

Hän katsoi ympärilleen. Kaikkialla oli hiljaista, — kyllä hän oli hyvin
kaukana.
Hän oli matkalla maailmalle, oli todellakin paennut! Hän tahtoi
kulkea, kulkea yhä edelleen — eikä koskaan palata!

Mutta hän ei ollut saanut mitään mukaansa. Kaksikymmentä


kruunua oli jäänyt kotiin ja välipalakin, valmiiksi laitetut voileivät
olivat hänen huoneessaan odottamassa. Ne hän oli aikonut ottaa
mukaansa evääksi. Nyt hän saisi nähdä nälkää ja kärsiä puutetta!

Mutta tämä oli ihan oikein. Hänen piti kärsiä puutetta. Tässä ei
auttanutkaan pelkkä rukoileminen. Ei, ensin hän saisi kärsiä jotakin
oikein kovaa. Nälkää ja puutetta, rahattomana, — jos hän tätä
kestäisi jonkun aikaa, edes muutamia päiviä, niin ehkä Jumala silloin
hiukan antaisi arvoa hänelle…!

Niin, parasta oli taas lähteä. Yöksi piti piiloutua metsään. Ei se


mitään vaikeata ollutkaan. Eivät he häntä löytäisi. Kun hän pääsee
ensimäiseen kaupunkiin, niin sieltä hän kirjoittaa isälle, että antavat
hänen jatkaa matkaansa, eivätkä suotta takaa aja. Hän toivoi vaan
saavansa kärsiä ja omin voimin päästä eteenpäin. Kerran, kun hän
luulee rikoksensa sovitetuksi ja omin päin on joksikin päässyt, niin
silloin hän tulee kotiin. Kyllä isä antaisi hänen menetellä näin, kun
hän vaan kirjoittaisi oikein vakavasti ja järkevästi.

Monen vuoden kuluttua hän palaisi isän ja äidin, Johannan ja


Drean luo — kunniallisena miehenä.

Niin — parasta oli heti lähteä eteenpäin!

Hän katsoi taivaalle; se oli kirkas ja sininen. Aurinko alkoi lähestyä


tunturia. Hän tunsi päätöksensä jälkeen muuttuneensa paremmaksi
ihmiseksi. Taas Jumala muistui mieleen. Ei hän sentään tahtoisi nyt
pyytää Jumalalta apua — sehän olisi halpamaista. Mutta "Isämeidän
rukouksen" hän aikoi lukea. Siitä Jumala kyllä ymmärtäisi hänen
tarkoituksensa.

Mikko Tiukkatuuli luki "Isämeidän". Sitten hän jatkoi matkaansa.

Puoliyhdeksän ajoissa illalla tuli Mikko Tiukkatuulen isä


kaupunginvouti Bechille.

— Olivatko he nähneet Mikkoa heillä tänään?

— Olivat kylläkin. Viiden aikaan iltapäivällä hän oli ollut heillä


puolen tunnin ajan. Sittemmin emme ole nähneet häntä, eikö hän
ole tullut kotiin?

— Ei, poika on ollut kotoa poissa koko päivän. Mikko Tiukkatuulen


isä meni. Kun hän oli kulkenut kappaleen matkaa katua alaspäin,
juoksi joku hänen järjestään.

— Anteeksi, herra kamreeri!

— Sinä, Antti!

— Niin, minä — minä tahdoin vaan, minusta tuntui, minä aijon


sanoa
Teille, että Mikko oli minun luonani tänään…

— Niin, poikaseni, minä kuulin sen. Tiedän myöskin, minkä vuoksi.


Rehtori Holst on ollut luonani ja kertonut kaikki.

— Niin — mutta Mikko — hän sanoi — hän pelkäsi kovin…

— Pelkäsikö hän?
— Kyllä, hän pelkäsi kovasti. Ja sitten hän sanoi, ettei uskaltaisi
mennä kotiin. Taikka oikeastaan hän tahtoi — tahtoi…

— Herran nimessä, mitä hän tahtoi?

— Karata kotoa.

Näytti silta, kuin Mikko Tiukkatuulen isä olisi luullut jotakin


pahempaa; hän huokasi helpotuksesta. Mutta vain hetkiseksi mieli
keventyi. Hän kysyi:

— Tiedätkö, minne? Voithan ymmärtää, hyvä Antti, että minun


täytyy se saada tietää!

— En. Hän sanoi vaan tahtovansa kävellä johonkin eteläiseen


kaupunkiin. Sieltä hän menisi Amerikan laivaan. Hän sanoi aikovansa
kulkea talosta taloon.

Oli valoisa toukokuun ilta. Mikko Tiukkatuulen isä seisoi hiukan


aikaa miettien.

— Kuuleppas, Antti, tahdotko tehdä minulle suuren palveluksen?

— Hyvin kernaasti!

— Mene tilaamaan Olavi ajurilta minulle kaksi hevosta ja


ajoneuvot niin pian kuin suinkin. Pyydä häntä ajamaan heti meille!

— Kyllä!

Antti Bech juoksi. Mikko Tiukkatuulen isä meni kotiin.

Hiukkasta myöhemmin seisoi kaksi hevosta kamreerin oven


edessä. Toisen hevosen rattaille istui hän itse ja toisiin kärryihin
asettui hänen ensimäinen kirjurinsa.

— Nyt, Molstad, sanoi Mikko Tiukkatuulen isä, — ajatte Te


pohjoista tietä kello 12 asti ja tiedustelette joka talosta ja kaikilta,
kutka ikänä vastaanne sattuvat. Ell'ette saa mitään selvää kello 12,
niin palatkaa takaisin.

Molstad ajoi. Sitten Mikko Tiukkatuulen isä sanoi hyvästi


vaimolleen ja molemmille pikku tytöille, jotka seisoivat ovessa ja
itkivät.

Rattaanpyörät kolisivat siltarummun poikki.

Tunnin matkan päässä eteläisellä maantiellä hän tapasi erään, joka


luuli nähneensä jonkun. Myöhemmin erään akan. Kyllä hän oli
kohdannut pojan, aivan hiljan.

Ajoneuvot pyörivät eteenpäin.

Jonkun matkan päässä tuli vastaan heinäkuorma.

Maalaisäijä käveli kuorman vieressä.

— Et suinkaan sinä ole tavannut erästä kaupunkilaispoikaa täällä


tiellä? Pientä nasikkaa…

— Olen kai, herra kamreeri! Tuolla se poika makaa


heinäkuormalla. Se nukkui niin makeasti. Nostinhan tuon ylös, kun
istui ja itki tuolla maantien vieressä ruikuttaen väsymystä. Ehkä se
onkin oma poikanne?

— Niin on.
— Se väitti, tuota noin, ettei hänellä ole kotia, eikä mitään,
raukalla.

Korkealla heinäkuormalla nukkui Mikko Tiukkatuuli:

— Pyysikö hän päästä ajamaan sinun kanssasi?

— Eikös mitä! Eteenpäinhän se sanoi aikovansa. Siksi aikaa vaan


pyysi lepäämään heinäkuormalle, kun minä käväisisin siellä niin
Seppälässä. Palkkioksi tahtoi pidellä hevosta. Kun tulin takaisin, —
noin se makasi, nähkääs — ja nukkui. Ja annoinhan minä sen maata!

— - Seuraavana päivänä tuli rehtori laskentotunnilla luokkaan.


Opettaja Lange tervehti ja hymyili. Rehtori hymyili myöskin ja astui
opettajain paikalle.

— Minun täytyy tunnustaa sinulle, Antti Bech, että me eilen


syytimme sinua väärin. Toveriesi pitää saada tietää, että et sinä ole
harjoittanut petosta; me erehdyimme. Omasta puolestani tahdon
vielä lisätä: olen kovin hyvilläni, koska entinen varma luottamukseni
sinuun täten vahvistuu, ett'et sinä voisi ryhtyä tällaisiin kepposiin.
Ole hyvä, Antti Bech, ja tule tänne!

Antti Bech astui opettajan luo.

— Minä pyydän sinulta anteeksi, koska olen tehnyt sinulle väärin.


Anna minulle kättä, niin minä tiedän saavani anteeksi!

Antti Bech ojensi kätensä.

Rehtori tarttui siihen toisella kädellään, ja toisella hän silitti


Antin kiharaista päätä.
— Niin, pojat, sanoi rehtori, kun Antti Bech oli mennyt paikalleen,
— näyttäkää meille, että te kaikki voitte seurata Antti Bechin
esimerkkiä — ja pitää kilpenne tahratonna.

Ovea lähestyessään sanoi rehtori:

— Mikko, seuraa minua hetkeksi!

Mikko Tiukkatuuli meni rehtorin mukana ulos ovesta pitkin


käytäviä kansliaan.

Hän seisoi taas tuossa kapeassa, korkeassa huoneessa, jossa


näkyi vaan tiukkoja kirjanselkiä seinillä. Rehtori Holst istui ja katseli
häntä.

Mikko Tiukkatuuli näytti laihalta ja kalpealta.

— No, Mikko! sanoi rehtori — kai sinä olet joka lauantai jäljentänyt
laskuesimerkkiä?

— Olen. Joka lauantai.

— Niin kai. Minä olen pyytänyt opettaja Langea opettamaan sinulle


yksityisesti kahtena tuntina viikossa laskentoa. Koeta tehdä
parastasi. Tutkinto on jo kuukauden päästä.

— Koetan.

— No, kai me nyt olemme yhtä mieltä siitä, ettei enää tapahdu
mitään petosta, Mikko?

— Kyllä.
— Silloin ei sinun tarvitse kestää sellaista päivää kuin eilinen oli.
Eikö totta, ethän sinä toista sellaista halua?

— En.

— Minä olen puhutellut isääsi, poikaseni. Me olemme siinä uskossa


molemmat, että sinusta vielä tulee kunnon mies! Hyvästi, poikaseni!

Mikko Tiukkatuuli itki raivoisasti. Rehtori meni ovelle pojan luo ja


silitti hänen tukkaansa.

Mikko Tiukkatuuli nyyhkytti; rehtori odotti häntä menemään,


mutta pojalla oli jotakin sanottavaa, nyyhkytysten lomassa hän
lopulta sai äänensä kuuluville, hän kumarsi syvään, ojensi kätensä
rehtorille ja sanoi:

— Pa — aljon — kii — iitoksia!

Kotona oli päivällisruokana suuri, punainen häränpaisti, kastiketta,


puolukkahillaa ja perunoita, — vaikka olikin tuorstai, jolloin muuten
syötiin kalaa.
TAPPELUA.

Minä en väitä mitään. Minä vaan kysyn, mistä sinä olet saanut minun
laskuni — ellet sinä ole jäljentänyt sitä!

Näin Simo Selmer rehenteli koulun pihalla. Antti Bech seisoi hänen
edessään uhitellen.

— Katsoppas, Simo, se asia ei koske sinua.

— Vai ei. No, arvatenkin on se parasta.

— Sanoppas, mies, mitä sinä sillä tarkoitat? Mikä on parasta? Sitä


juuri tahtoisin kysyä, ymmärrätkös?

Simo Selmer katseli naureskellen poikajoukkoa. Koko luokka oli


kerääntynyt heidän ympärilleen.

— Ja minä vastaan, että lienee parasta, ell'ei ollenkaan enää tutki


koko juttua.

— Rehtori on sen kyllä tutkinut.

— Sen huomaan.
— Miten niin, huomaat?

— Rehtorin olevan erilaisen.

— Kuinka, erilaisen?

— Noo — olisipa asia koskenut jotakuta meistä, toisista, eikä


hänen lempipoikaansa, niin kyllä olisi saatu nähdä toista!

— Miten niin, toista?

— Onpa sinulla kyselemistä!

Antti Bech piti nyrkkejään housuntaskuissa, aivan rauhallisena,


katsomatta ympärilleen. Hän tuijotti vaan suoraan Simo Selmerin
naamaan ja sanoi:

— Niin, minä kysyn siksi, kunnes sinä vastaat!

Siksi, että sinun täytyy vastata,

— Täytyy — oho!

— Niin juuri — täytyy. Mitä sinä sillä tarkoitit, että olisi saatu
nähdä toista?

— Minä tarkoitan sitä, mitä tarkoitan. Antti Bech astui nyt ihan
hänen nenänsä eteen.

— Niin, näetkös, jo riittää. Mutta minä kysyn vielä, luuletko sinä


minun harjoittaneen petosta?

— Minä en luule mitään. Minä tiedän, että minun laskuni oli sinun
vihossasi.
— Mutta kun minä sanon — ja rehtori sanoo, — että se on
sattuma!

— Niin sanon minä, että se on merkillinen sattuma.

— Miten, merkillinen?

— Hyvin merkillinen.

Koko poikajoukko nauroi. Antti Bech veti toisen nyrkkinsä


taskustaan.

— Puhu suusi puhtaaksi ja sano suoraan ajatuksesi.

— Kovinpa sinä pidätkin tärkeänä minun "ajatustani", hyvä mies!

— Minä en siedä sinun mutinaasi minun laskuistani kauempaa.


Ellet sinä tyydy rehtorin selitykseen asiasta, niin et sitä minultakan
saa. Tämän jutun pitää päättyä tähän. Siksi pitää sinun puhua suusi
puhtaaksi, jotta tulee jonkunmoinen päätös.

— Ahaa, sinä vaadit tappelua!

— Niin, se on tarkoitukseni. Minä otan luokan todistajaksi, ell'et


sinä suoraan tunnusta rehtorin selitystä täydelliseksi ja hyväksi, niin
tapaamme toisemme Naularannassa tänään kello 4 ikäpuolella.

— Minä en pelkää tulla.

— Hyvä on!

Samassa pyörähti Antti Bech ympäri ja juoksi poikajoukosta ylös


koulun portaita. Oli jo soitettu luokkaan.
— Tappelua, pojat!

— Kunnollista sittenkin!

— Kello 4 siis Naularannassa!

— Mutta ainoastaan luokka. Ei muita.

— Selväähän se. Luokka juoksi innokkaana joukossa portaita ylös.

— Kyllä "Kilvoittelija" selkäänsä saa, sen takaan.

— No se nyt ei ole varmaa.

— Kyllä sille vaan selkäsauna hyvää tekisi, Simolle. Mitä hänen


tarvitsee sekaantua toisen asiaan!

— Mutta onko se nyt sitten laitaa!

— Luuletko sinä, että rehtori olisi pyytänyt anteeksi, jos Antti olisi
tehnyt petoksen?

— E — en…!

Svenningsen oli raivoissaan luokalla, kun he tulivat niin myöhään


sisään. Eikä luokan epätarkkuus liioin ollut omiansa lepyttämään
häntä — kirjelappusia kyhättiin ja kuljetettiin tunnilla —!

Jo viime talvena olivat Antti Bech ja Simo Selmer kerran


"kunnollisesti" tapelleet. Aiheena oli ollut Niko Makkaratikku. Sen
kerran oli Simo Selmer saanut selkäänsä. Kai hän nytkin saanee.
Simo Selmer oli paksu ja jäykkä, aika vahva. Mutta Antti Bech oli
sentään luokan vahvin poika. Simo Selmer taas oli täynnä juonia!
Niko Makkaratikun asian laita oli seuraava:

Niko Öien — "Makkaratikku" — oli Antti Bechin verivihollinen. Mistä


tämä vihamielisyys johtui, sitä ei tiedetty; vihamiehiä he vaan olivat.
Ei Antti Bech itsekään olisi kysyttäessä voinut selvittää, mistä se
johtui. Tosiasia vaan oli, että, jos hän tapasi Niko Makkaratikun
pohjoispuolella kaupunkia, niin tapella piti. Sitä kelpasi katsella, kun
hän taikka Niko oli jonkun seurassa. Jos he kohtasivat toisensa
kahden kesken, tarvittiin vaan pari haukkumasanaa ohi mennessä —
kuten:

— Odotappas, sinä tolvana! tai: — Vieläkö viimekertainen


selkäsauna raajoissasi kihelmöi?

Kun jompikumpi sattui olemaan joukon mukana, oli asia itsestään


selvä; toiset muodostivat kehän, ja nuo kaksi alkoivat tapella.

Toisinaan, kun Antti oli luokkatovereineen pohjoispuolella


kaupunkia hongottelemassa, näkivät he Niko Makkaratikun etäällä
äkkiä pujahtavan porttikäytävään tai häviävän jostakin
kadunkulmasta. Asia oli niin, että Niko säännöllisesti sai selkäänsä.
Antti Bechin tapa oli silloin aina äänekkäästi valittaa tovereilleen, että
taas oli hukkaan mennyt hyvä tilaisuus saada rökittää Niko
Makkaratikkua.

Mutta itseksensä hän iloitsi siitä. Ensiksikin, se oli aina hiukan


jännittävää joka kerta, — eihän voinut tietää, mitä temppuja Niko
Makkaratikku oli oppinut edellisestä kerrasta ja kuinka paljon
kansakoulutovereja hänellä oli takanaan; toiseksi, siksi — — no niin,
Niko Makkaratikku oli kasvoiltaan niin kummallisen kalpea, joka kerta
kun piti ottaa vastaan, ja silmissä niin kummallinen oudoksuvan
kysyvä katse, kun hän oli saanut selkäänsä. Kaikki tämä muistutti
Antti Bechille erästä runoa, jonka hän kerran oli lukenut; siinä
kerrottiin kuinka metsästäjä oli haavoittanut hirveä metsässä ja aikoi
leikata siltä kaulan poikki — — hänen oli hyvin vaikea sitä tehdä
eläimen katseen vuoksi!

Kaikesta huolimatta, Niko Makkaratikku oli ja pysyi vihamiehenä;


mikä siihen oli syynä, ei kukaan tiennyt. Antin luokkalaiset ja
kansakoulun pojat pitivät sitä vanhastaan varmana asiana. Se oli
kaupunkilaista sotakantaa, eikä sitä asiaa kannattanut syvemmältä
harkita.

— — Jouluaattona kertoi rouva Bech päivällispöydässä Öien'in


eukon olleen keittiössä surkeasti valittamassa, kuinka heille tulisi
köyhä ja kurja joulu, sillä mies oli työttömänä; ja rouva Bech oli
antanut hänelle Antin arkihousut — jotka kyllä olivat eheät ja
pitokuntoiset vielä. Varsinkin oli huonoa vaatteen puolesta: Niko
poika tuskin saattoi menua kouluun risoissansa.

Päästiin kolmanteen joulupäivään, joka lopultakin oli arkipäivä.

Luokan pojat yhtyivät. Antti Bech oli uusissa vaatteissaan,


liivintaskussa kaksikymmentä viisi äyriä; ne hän oli saanut Fredrik
sedältä. Tänään se oli uhrattava kakkuihin.

Nyt Otar Ingebrigtsen toi sellaisen mieliä kiihoittavan uutisen, että


kansakoulun poikien lumilinna alhaalla "Pitkässä Satamassa" oli
suurempi kuin heidän luokkalaistensa Bechin pihalla.

Koko joukko ryntäsi pohjoista kohti. Aivan oikein: Pitkässä


Satamassa kansakoululaisten linnoitus oli kohonnut hävyttömän
korkeaksi! Se oli jäästä ja lukuisista nyrkeistä tullut likaisen
kiiltäväksi; tosiaankin, sitä ei voisi valloittaa. Kansakoulun pojat
vilisivät sen kimpussa.

Vitkaan luokka lähestyi, kerääntyen puoliympyrään lähelle


linnoitusta.

Pari hyökkäävää poikaa vastakkaisilta puolilta alkoi syytää


haukkumasanoja ja vaatia tappeluun. Antti Bech seisoi alallaan ja
kuunteli. Äkkiä Simo Selmer ja pari muuta alkoi pökkiä häntä
kylkeen:

— Antti! tuolla on Makkaratikku! Etkö näe'? Karkaa kimppuun!

Matta Antti ei liikahtanut. Silloin toisetkin alkoivat huutaa:

— Kuules, Niko! Etkö sinä aijokaan pamppua paukuttaa tänä


jouluna?
Tässä seisoo Antti Bech ja pelkää sinua!

— Pelkää! huusi Antti; kierippäs tänne, Makkara!

Niko ei hievahtanut, likisteli vaan lunta linnoituksen muuriin, eikä


nähtävästi välittänyt hyökkäämisestä, vaikka hänen puoluelaisensa
ärsyttivät ja kehoittivat, Antin siirtyessä yhä lähemmäksi. Silloin Antti
äkkiä tokaisi:

— Makkaratikku pelkää turmelevansa uudet housunsa, — sillä ne


hän on perinyt minulta.

Kaikki pojat nauroivat; tunsivathan he Antti Bechin housut. Mutta


siinä tuokiossa oli Niko Makkaratikku Antti Bechin kimpussa ja
läimäytti häntä nyrkillään nenän alle, niin että Antti kaatui
taaksepäin, ja verta syöksyi nenästä. Niko mukiloi ihan silmittömässä
raivossa, joten Antti tointui vasta kun Niko istui hänen päällänsä,
vimmatusti nyrkillänsä pehmittäen hänen kasvojaan.

Kaikki tuntevat, miten tappelussa aivan äkkiä voi tulla pysäys,


josta vaan nuo kaksi tietävät. Nikon kuuma hengitys tunki ihan Antin
veriseen nenään; hän lakkasi lyömästä, ja molemmat huohottivat.

Juuri silloin huomasi Antti, että hän olisi voinut pyöräyttää Nikon
pois päältänsä, päästä itse päällepäin ja antaa runsaasti takaisin;
sillä hän näki, että Makkaratikku itki vimmoissaan ja oli melkein
tajuttomana. Mutta hän pysyi alallaan, irroitti toisen kätensä ja sai
sen liivintaskuunsa, josta otti hyppysiinsä viisikolmattaäyrisen.

— Lakkaa jo, hölmö!

Ja Makkaratikku hellitti. Antti pujotti salaa kaksikymmentäviisi


äyriä Makkaratikun kouraan, ja sitten he pysyttelivät hiljaa, toinen
alla, toinen päällä. Yht'äkkiä pyöräytti Antti Nikon pois päältään ja
nousi ylös. Toiset huusivat yhtä ja toista, mutta Makkaratikku juoksi
tiehensä, ja Antti pesi lumella veren pois nenästään. Hän ei puhunut
mitään. Sen kerran perästä ei hän koskaan tapellut Niko
Makkaratikun kanssa.

Tämä juttu kahdestakymmenestä viidestä äyristä tuli jollain lailla


poikien korviin.

Simo Selmer kirjoitti kerran tunnilla kirjelipun ja lähetti sen Ville


Gabrielsenille; siinä hän kertoi, että Antti Bech oli 25 äyrillä ostanut
itsensä vapaaksi selkäsaunasta Niko Makkaratikulta. Tämä lappu
joutui Antti Bechin käsiin, ja siitä oli seurauksena Antti Bechin ja
Simo Selmerin tappelu Naularannassa.
Tämä oli tapahtunut edellisenä talvena. Silloin juuri "kilvoittelija"
sai selkäänsä; mutta siitä oli nyt jo puolitoista vuotta; siinä ajassa
olivat asianhaarat paljon ehtineet muuttua.

— - Puolineljältä kerääntyi suuri poikajoukko Naularantaan. Siellä


oli mahdottoman suuri lankkuaidalla ympäröitty ala, jonkinmoinen
piha, jossa oli puulattia erään kauppaliikkeen kahden
varastohuoneen välillä. Varastohuoneiden seinustalla oli
kaksinkertainen rivi tyhjiä tynnyreitä. Näille istuttiin neuvottelemaan,
nuijien saappaankoroilla tyhjiä tynnyreitä, jotta ne kumisivat.
Aituuksen toisesta päästä johti venesilta alas rantaan. Sillalla Söyrinki
Miehentappaja ja muutamat muut puuhasivat pyydysvehkeineen ja
syöttineen. He onkivat rapuja, odottaissaan.

Kaikki satamat olivat mukavia kokouspaikkoja pojille tähän


vuodenaikaan, ne kun olivat autioina melkein kaikki. Ja varsinkin
tämä
Naulasatama, sillä se oli etäisin, kaupungin eteläisimmässä kolkassa.
Ja Naulasataman kaitsija, Hans Bentsen, oli harvinaisen hauska
mies.

Vihdoin tuli Simo Selmer Otar Ingebringtsenin kanssa. Hän oli


hiukan kalpea; mutta tahtoi näyttää kuin ei olisi millänsäkään koko
asiasta, istui tynnyrille, puheli ja nauroi. Kun Söyrinki Miehentappaja
ja muut pojat sillalla kuulivat Simo Selmerin tulleen, jättivät he
ravunpyydystämisen ja astelivat toisten luo.

Kaukaa kaupungista kuului kirkontornin kellon lyönti. Se löi neljä.

Juuri silloin saapui Antti Bech. Hänen mukanansa oli Mikko


Tiukkatuuli.
— Onpa se merkillistä, kuinka nuo kaksi aina roikkuvat yhdessä!
sanoi
Matti Johnsgaard Ville Gabrielsenille.

— Etkö ole huomannut, — sanoi Ville Gabrielsen — että Antti Bech


on viime aikoina auttanut Mikko Tiukkatuulta kirjoituksissa?

— Niin, sitähän minäkin…

Antti Bech astui suoraan sen tynnyrin luo, jolla Simo Selmer istui
ja potki kantapäillään.

— Viimeisen kerran minä vaadin sinua sanomaan, — väitätkö sinä


minun pettäneen?

— En ole mitään sanonut. Enkä tahdo mitään väittää.

— Tuollaista roskapuhetta, ett'et sinä muka ole mitään sanonut, ei


hyväksytä. Minä kysyn…

— Pidä kitasi kysymyksinesi! huusi Simo Selmer, hypäten alas


tynnyriltä; samassa hän töykkäsi Antti Bechiä vatsaan.

Antti astui taaksepäin. Hän keitti takin yltään ja seisoi valmiina


paitahihasillaan. Pojat kerääntyivät tiheään piiriin heidän ympärilleen.

— Nyt saat hyökätä! sanoi Antti. Mutta Ville Gabrielsen astui esiin
joukosta ja sanoi juhlallisesti:

— Ensin on sovittava, ettei saa kampata, eikä panna jalkaa eteen,


eikä puskea.

— Niin, sanoi Matti Johnsgaard, joka asettui Villen viereen — ja


kun painitte, niin pitää vaihtaa altaheittoa ja päältäheittoa!
— Ei, — kumpi ensin puolensa pitää! huusi Otar Ingebrigtsen.

— Niin minustakin! myönsi pari muuta. Antti ja Simo tähystivät


toisiaan, nyrkit puristettuina, muiden luistellessa altaheitosta ja
päältäheitosta. Aina vähä väliin kuului Ville Gabrielsenin huuto:

— Järjestystä pitää noudattaa! Järjestystä pitää noudattaa!

— Se on tietty, mutta altaheitto ja päältäheitto….

— Nyt voitte alkaa! Imusi Otar Ingebrigtsen. — Me asetumme


kaikki piiriin ympärille. Tietysti pitää järjestystä noudattaa, petosta ei
hyväksytä. Kas — niin, hiukan taaksepäin — noin. Nyt minä lasken
kolmeen:

— Yks, kaks, kolm…

— Ei, ei, odotappas, poika! Mikko Tiukkatuuli syöksyi esiin, —


Simolla on kivi nyrkissä! Hyväksytäänkö sitä?

Tulipunaisena Simo Selmerin täytyi pudottaa pyöreä kivi


kumpaisestakin kourastaan.

— Yks, kaks, kolme!

He syöksyivät toistensa kimppuun. Simo Selmer, pää alhaalla


käsivarsien välissä, ja nyrkit kävivät kuin höyryveneen propelli. Mutta
Antti Bech iski nyrkillään altapäin keskelle toisen naamaa. Se oli
hänen temppunsa! He olivat harjaantuneita miehiä kumpikin, ja
tappelu kävi yhä tulisemmaksi; oikealla kädellä he löivät ja
vasemmalla puolustivat itseään. Kumpikaan ei päässyt antamaan
toiselle sukkelata nenä-iskua. Kiihkoissaan he pyörivät ympäri, jotta
poikien piirin piti siirtyä paikasta paikkaan.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like