100% found this document useful (9 votes)
51 views

Beginning XML With C# 7: XML Processing and Data Access For C# Developers 2nd Edition Bipin Joshi (Auth.) Ebook All Chapters PDF

Bipin

Uploaded by

ayaiirrafo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (9 votes)
51 views

Beginning XML With C# 7: XML Processing and Data Access For C# Developers 2nd Edition Bipin Joshi (Auth.) Ebook All Chapters PDF

Bipin

Uploaded by

ayaiirrafo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Download the full version of the textbook now 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/

Explore and download more textbook at https://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/

textbookfull.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/

textbookfull.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/

textbookfull.com

Powerarchy Understanding The Psychology Of Oppression For


Social Transformation Melanie Joy

https://textbookfull.com/product/powerarchy-understanding-the-
psychology-of-oppression-for-social-transformation-melanie-joy/

textbookfull.com
Food Aroma Evolution: During Food Processing, Cooking, and
Aging 1st Edition Matteo Bordiga

https://textbookfull.com/product/food-aroma-evolution-during-food-
processing-cooking-and-aging-1st-edition-matteo-bordiga/

textbookfull.com

Blockchain for Distributed Systems Security 1st Edition


Sachin S. Shetty

https://textbookfull.com/product/blockchain-for-distributed-systems-
security-1st-edition-sachin-s-shetty/

textbookfull.com

Understanding Dying, Death, and Bereavement 9th Edition


George E. Dickinson

https://textbookfull.com/product/understanding-dying-death-and-
bereavement-9th-edition-george-e-dickinson/

textbookfull.com

Boosting Your Health with Probiotics Delicious Simple and


Easy Probiotic Recipes with Step by Step Guide Martha
Stephenson
https://textbookfull.com/product/boosting-your-health-with-probiotics-
delicious-simple-and-easy-probiotic-recipes-with-step-by-step-guide-
martha-stephenson/
textbookfull.com

Let Them See You The Guide for Leveraging Your Diversity
at Work Porter Braswell

https://textbookfull.com/product/let-them-see-you-the-guide-for-
leveraging-your-diversity-at-work-porter-braswell/

textbookfull.com
Machine Learning Techniques for Space Weather 1st Edition
Enrico Camporeale (Editor)

https://textbookfull.com/product/machine-learning-techniques-for-
space-weather-1st-edition-enrico-camporeale-editor/

textbookfull.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
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
■ 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
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
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
Random documents with unrelated
content Scribd suggests to you:
small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.

You might also like