FOR XML in SQL Server 2005 289 Executing FOR XML Queries from ADO.NET 290 XML Data Type in SQL Server 2005 298 Working with XML Data Type Columns from ADO.NET 303 Using XML Schema on the
Trang 2Professional ASP.NET 2.0 XML
Trang 4Professional ASP.NET 2.0 XML
Thiru Thangarathinam
Trang 5Copyright © 2006 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN-13: 978-0-7645-9677-3
ISBN-10: 0-7645-9677-2
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form
or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as mitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior writ-ten permission of the Publisher, or authorization through payment of the appropriate per-copy fee tothe Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978)646-8600 Requests to the Publisher for permission should be addressed to the Legal Department, WileyPublishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, oronline at http://www.wiley.com/go/permissions
per-LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHORMAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY ORCOMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WAR-RANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULARPURPOSE NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONALMATERIALS THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLEFOR EVERY SITUATION THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUB-LISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONALSERVICES IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENTPROFESSIONAL PERSON SHOULD BE SOUGHT NEITHER THE PUBLISHER NOR THE AUTHORSHALL BE LIABLE FOR DAMAGES ARISING HEREFROM THE FACT THAT AN ORGANIZATION
OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE
OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHERENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR REC-OMMENDATIONS IT MAY MAKE FURTHER, READERS SHOULD BE AWARE THAT INTERNETWEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHENTHIS WORK WAS WRITTEN AND WHEN IT IS READ
For general information on our other products and services please contact our Customer Care ment within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317)572-4002
Depart-1MA/QT/QR/QW/IN
Library of Congress Control Number is available from the publisher
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related
trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates, inthe United States and other countries, and may not be used without written permission All othertrademarks are the property of their respective owners Wiley Publishing, Inc., is not associated withany product or vendor mentioned in this book
Wiley also publishes its books in a variety of electronic formats Some content that appears in print maynot be available in electronic books
Trang 6About the Author
Thiru Thangarathinamworks for Intel Corporation in Phoenix, Arizona He is an MCAD (MicrosoftCertified Application Developer) and specializes in architecting and building Distributed N-Tier applica-tions using ASP.NET, Visual C#.NET, VB.NET, ADO.NET, and SQL Server 2000 He has co-authored anumber of books for Wrox Press in NET technologies Thiru is also a regular contributor to print and
online magazines such as Visual Studio Magazine, Visual Studio NET Professional, SQL Server
Professional, DevX, ASPToday.com, 15seconds.com, and Developer.com At Intel, he is part of the teamthat is focused on developing the Enterprise Architecture and Service Oriented Architectures for Intel
He can be reached at thiru.thangarathinam@intel.com
Trang 8Quality Control Technician
Brian H Walls, Joe Niesen
Proofreading and Indexing
TECHBOOKS Production Services
Trang 10Administration and Management 35
Design Goals for XML Support in NET Framework 2.0 41
Trang 11Chapter 4: Reading and Writing XML Data Using XmlReader and XmlWriter 61
Summary 130
XML Document Loaded in a DOM Tree 132
Trang 12Contents
Working with XmlDocument Class 139 Programmatically Creating XML Documents 149 The XmlDocumentFragment Class 159 XPath Support in XML DOM 159 Validating XML in an XmlDocument 171
Advanced XSLT Operations 207 Debugging XSLT Style Sheets 209
Trang 13FOR XML in SQL Server 2005 289 Executing FOR XML Queries from ADO.NET 290 XML Data Type in SQL Server 2005 298 Working with XML Data Type Columns from ADO.NET 303 Using XML Schema on the Client 317 Multiple Active Result Sets (MARS) in ADO.NET 323 XML Data Type and a DataSet 326
Summary 333
Chapter 11: Building an Airline Reservation System
Trang 14Asynchronous Invocation of Web Services from a Client Application 443 Asynchronous Invocation of Web Services from a Browser Using IE Web Service Behavior 448 Asynchronous Web Service Methods 454 Controlling XML Serialization Using IXmlSerializable 457 Using Schema Importer Extensions 460 Miscellaneous Web Service Features in NET
New Configuration Sections in ASP.NET 2.0 468 WebConfigurationManager Class 471 Retrieving Configuration from Predefined Sections 473 Encrypting and Decrypting Configuration Sections 478 Enumerating Configuration Sections 482 Reading Configuration Sections 483 Creating a Custom Configuration Section 487 Built-in Configuration Management Tools 491
Summary 495 Chapter 15: Building a ShoppingAssistant Using XML Web Services 497
Trang 15Contents
Implementation of ShoppingAssistant Web Application 513 Using Asynchronous Invocation of Web Services and Windows Service 526 Modifying the ShoppingAssistant Web Pages to Consume XML Files 531 Implementation of FileSystemWatcher to Facilitate Reporting Data Collection 532 Putting It All Together 538
Summary 539
Trang 16I would like to acknowledge my wife Thamiya, my parents and my family for their constant supportand encouragement throughout while I spent nights and weekends working on this book
Trang 18This book will cover the intersection between two great technologies: ASP.NET and XML
XML has been a hot topic for some time The massive industry acceptance of this W3C Recommendation,which allows data communication and information storage in a platform independent manner, has beenastounding XML is seen and used everywhere—from the display of data on various browsers using thetransformation language XSLT, to the transport of messages between Web services using SOAP
.NET is Microsoft’s evolutionary and much vaunted new vision It allows programming of applications
in a language independent manner, the sharing of code between languages, self-describing classes, andself-documenting program code to name but a few of its capabilities .NET, in particular ASP.NET, hasbeen specifically designed with Web services and ease of development in mind With the release of NET2.0 Framework, NET includes significant enhancements to all areas of ASP.NET For Web page develop-ment, new XML data controls like XmlDataSource, and TreeView make it possible to display and editdata on an ASP.NET Web page without writing code reducing the required amount of code by as much
as 70% in some cases ADO.NET 2.0 includes many new features that allow you to leverage the newXML features introduced with SQL Server 2005 (the next major release of SQL Server)
To achieve this exciting new Web programming environment, Microsoft has made extensive use of XML
In fact, no other technology is so tightly bound with ASP.NET as XML It is used as the universal dataformat for everything from configuration files to metadata, Web Services communication, and objectserialization All the XML capabilities in the System.Xml namespace were significantly enhanced foradded performance and standards support The new model for processing in-memory XML data,editable XPathNavigator, new XSLT processor, strong typed support for XmlReader, and XmlWriterclasses, are some of the key XML related improvements Connected to this is the new support for XMLthat ADO.NET 2.0 has Because of the new ADO.NET 2.0 features, the programmer now has the ability
to access and update data in both hierarchical XML and relational database form at the same time
Who This Book Is For
This book is aimed at intermediate or experienced programmers who have started on their journeytoward ASP.NET development and who are already familiar with XML While I do introduce the reader
to many new ASP.NET 2.0 concepts in Chapter 2, this book is not intended as a first port of call for thedeveloper looking at ASP.NET, since there are already many books and articles covering this area.Instead, I cut straight to the heart of using XML within ASP.NET Web applications To get the most out
of the book, you will have some basic knowledge of C# All the code examples will be explained in C#
In a similar vein, there are many books and articles that cover the XML technologies that you will need
to use this book I assume a general knowledge of XML, namespaces, and XSLT, and a basic ing of XML schemas
Trang 19understand-What This Book Covers
This book explores the array of XML features and how they can be used in ASP.NET for developing Webapplications XML is everywhere in the NET Framework, from serialization to Web services, and fromdata access to configuration In the first part of this book, you’ll find in-depth coverage of the key classesthat implement XML in the NET platform Readers and writers, validation, schemas, and XML DOM arediscussed with ASP.NET samples and reference information Next the book moves on to XPath and XSLTransformations (XSLT), XML support in ADO.NET and the use of XML for data display
The final part of this book focuses on SQL Server 2005 XML Features, XML Serialization, XML Web services, and touches on XML based configuration files and its XML extensions You’ll also find a couple
of case studies on the use of XML related features of ASP.NET and Web services that provide you with areal life example on how to leverage these features
How This Book Is Str uctured
The book consists of 15 chapters including two case studies The book is structured to walk the readerthrough the process of XML development in ASP.NET 2.0 I take a focused approach, teaching readersonly what they need at each stage without using an excessive level of ancillary detail, overly complextechnical jargon, or unnecessary digressions into detailed discussion of specifications and standards Abrief explanation of each of the chapters is as follows:
An Introduction to XML
XML finds several applications in business and, increasingly, in everyday life It provides a commondata format for companies that want to exchange documents using Web services This chapter is aboutXML as a language and its related technologies The XML technologies that I will specifically introduce
in this chapter are: XML document elements, namespaces, entities, DTD, XDR, XSD, XSD schema datatypes, XSLT, XML DOM, XPath, SAX, XLink, XPointer, and XQuery
An Introduction to ASP.NET 2.0
In Chapter 2, I aim to give the reader an overview of the new features of ASP.NET 2.0 I will highlightthe new ASP.NET page architecture, new data controls, and code sharing features I ask, “What is masterpages” and go on to talk about how master pages and themes aid in creating consistent Web sites Later
on, I look at security controls and Web parts framework and illustrate how ASP.NET 2.0 enables 70%code reduction Finally, I will look at the new caching and administration and management functionali-ties of ASP.NET 2.0
XML Classes in the NET Framework
In Chapter 3, I take a brisk walk through all the new XML classes in the NET Framework, which will bediscussed in more detail throughout the rest of the book
Microsoft has introduced several new applications of XML in NET 2.0 and has also done some tive work to improve the core XML API I start with a discussion on the use of XML in configurationfiles, DOM, XSD schema validation, XSLT transformations, XML serialization, Web services, and XML
innova-Introduction
xviii
Trang 20support in ADO.NET and look at the namespaces and classes that are available for this purpose I willalso illustrate the new ASP.NET configuration enhancements and take a quick look at the configurationclasses in NET Framework 2.0
Reading and Writing XML
Chapter 4 starts a section of chapters (4 through 6) that look at the functionality contained within theSystem.Xml in more detail
In particular, here I look at the fast, forward-only read-only mechanisms provided by the NETFramework for reading and writing XML documents, namely the XmlReader and XmlWriter classes Iexplore the new XML reading and writing model and talk about the various ways using, which you canread and write XML data I also go onto discuss node order, parsing attributes, customizing reader andwriter settings, white spaces handling, and namespace handling, and other namespace support
Validating XML
In Chapter 5, I take a look at different options for the XML validation grammars: DTDs, XDR schemas,and XSD schemas I also go on to look at all the ways you can create an XSD schema in Visual Studio2005: using the XML designer, from a DTD, using the XSD generator, from an XML document, from anXDR schema, or from an assembly I also discuss the schema object and see how to link XML documents toDTDs, XDR schemas, and XSD schemas, and how to then perform validation using the XmlReaderSettings
in conjunction with the XmlReader class I also illustrate the use of the XmlSchemaSet class to keep a cache
of schemas in memory, to optimize performance, and also deal with unqualified/namespace-qualified tent in XML documents
con-XML DOM Object Model
In Chapter 6, I look at the DOM functionality within the NET Framework provided within the System.Xmlnamespace of classes I look at programmatically creating XML documents, opening documents fromURLs, or strings in memory, and searching and accessing the contents of these documents, before serializ-ing them back out to XML strings I also take a look at the differences between the XmlDocument objectand the XmlReader and XmlWriter classes, and where using each is more appropriate Finally, I demon-strate the XPath capabilities of the XmlDocument class and also highlight the new editing capabilities ofthe XPathNavigator class to modify an XML document in memory
Transforming XML Data with XSLT
The NET Framework provides robust support for XSLT and XPath processing and with NETFramework 2.0, the XSL support has been completely redesigned and a new XSLT processor is intro-duced In Chapter 7, I look at the technologies used for XSL transformations in the NET Framework,namely the System.Xml.Xsl namespace, and System.Xml.XPath namespaces, as well as the newly intro-duced XslCompiledTransform class The NET Framework fully supports the XSLT and XPath specifica-tion as defined by the W3C, but also provides more helpful extensions to these specifications, whichenhance the usability of style sheets within NET applications To this end, I look at using embeddedscript with <msxsl:script> for transforming XML documents and show how to extend style sheets withextension objects Towards the end of the chapter, I discuss advanced XSLT operations such as how topass a node set to a style sheet and how to resolve external style sheets using XmlResolver
Introduction
xix
Trang 21XML Support in ADO.NET
In Chapter 8, I start to move away from the realm of the System.Xml namespace of classes, to explore thebroader picture of how XML is used in NET specifically from ADO.NET, the data access technology ofchoice
Chapter 8 looks at the role of XML in ADO.NET 2.0 and highlights the new XML related features ofADO.NET I cover the capabilities of the DataSet and DataTable classes, including reading and writingXML, and programmatically accessing or changing its XML representation I highlight how to synchro-nize DataSets with XmlDataDocuments and why you would do so I also cover the creation of stronglytyped DataSets and their advantages Finally, I take a glimpse at how to access some of the new XMLfeatures available in SQL Server 2005 from ADO.NET
XML Data Display
The XML support in ASP.NET provides excellent support for storing, retrieving and rendering XML
I start with looking at the new web.sitemap file that allows you to store the hierarchy of a Web site andleverage that to drive the navigation structure of a Web site Then, I go on to discuss the features of newXML data controls such as XmlDataSource, TreeView, and GridView for consuming and displayingnative XML directly in the browser Finally, I also introduce the new ASP.NET 2.0 script callback featurefor retrieving XML data directly from the browser without refreshing the page
SQL Server 2005 XML Integration
With the release of SQL Server 2005, XML support just got better and SQL Server 2005 provides powerfulXML query and data modification capabilities over XML data To start with, I introduce the new XMLfeatures of SQL Server 2005 including the FOR XML clause enhancements, XQuery support, and theXML data type Then I go on to discuss the execution of FOR XML queries from within ADO.NET bothsynchronously and asynchronously I also discuss the steps involved in working with typed and
untyped XML data type columns Finally, I illustrate how to retrieve XSD schemas from a typed columnusing ADO.NET and also focus on MARS and OPENXML() functions
Building an Airline Reservation System using ASP.NET 2.0 and SQL Server 2005
This case study ties together all the concepts including XML DOM, XML support in ADO.NET, XSLTfeatures in NET, XML data display, that have been covered so far in this book The focus of this casestudy is on incorporating these XML features in a real world airline reservations Web site and showcas-ing the best practices of using these XML features I also discuss the N-Tier design methodology andillustrate how to leverage that to create an extensible and flexible airline reservations system
XML Serialization
In Chapter 12, I look at serializing XML documents as XML data using the XmlSerializer class from theSystem.Xml.Serialization namespace More specifically, you create serializers, and then serialize and deseri-alize generic types, complex objects, properties, enumeration values, arrays and composite objects I alsolook at serializing and deserializing with nested objects, followed by formatting XML documents, XMLattributes, and text content Towards the end of the chapter, I discuss the steps involved in improving theserialization performance by pregenerating assemblies using the new XML serializer generator tool
Introduction
xx
Trang 22ASP.NET 2.0 Configuration
In Chapter 14, I introduce the new configuration management API of ASP.NET 2.0 that enables users toprogrammatically build programs or scripts that create, read, and update settings in web.config andmachine.config files I also go on to discuss the new comprehensive admin tool that plugs into the exist-ing IIS Administration MMC, enabling an administrator to graphically read or change any setting withinour XML configuration files Throughout this chapter, I focus on the new configuration managementclasses, properties, and methods of the configuration API and also provide examples on how to usethem from your ASP.NET applications
Building a ShoppingAssistant using XML Web Services
This chapter is based on a case study named ShoppingAssistant, which provides one stop shopping forconsumers that want to find out information such as the products that are on sale, availability of prod-ucts in different stores, comparison of the price of the product across different stores and so on In thiscase study, I demonstrate how to leverage Web services in a real world Web application by using asyn-chronous Web service invocation capabilities in conjunction with other NET features such as XMLSerialization, FileSystemWatcher, and Timer component
What You Need to Use This Book
All of the examples in this book are ASP.NET samples The key requirements for running these tions are the NET Framework 2.0 and Microsoft Visual Studio 2005 You also need to have SQL Server
applica-2005 server along with the AdventureWorks sample database installed to make most of the sampleswork A few examples make use of SQL Server 2005 Express database
The SQL Server examples in this book utilize integrated security to connect to the SQL Server database,
so remember to enable integrated authentication in your SQL Server This will also require you to turn
on integrated Windows authentication (as well as impersonation depending on your configuration) inASP.NET Web sites
Trang 23Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.
As for styles in the text:
❑ We highlight new terms and important words when we introduce them.
❑ We show keyboard strokes like this: Ctrl+A
❑ We show file names, URLs, and code within the text like so: persistence.properties
Source Code
As you work through the examples in this book, you may choose either to type in all the code manually
or to use the source code files that accompany the book All of the source code used in this book is able for download at http://www.wrox.com Once at the site, simply locate the book’s title (either byusing the Search box or by using one of the title lists) and click the Download Code link on the book’sdetail page to obtain all the source code for the book
avail-Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is 0-7645-9677-2 (changing to 978-0-7645-9677-3 as the new industry-wide 13-digit ISBN numbering system is phased in by January 2007).
Once you download the code, just decompress it with your favorite compression tool Alternately, youcan go to the main Wrox code download page at http://www.wrox.com/dynamic/books/
download.aspxto see the code available for this book and all other Wrox books
Errata
We make every effort to ensure that there are no errors in the text or in the code However, no one is perfect, and mistakes do occur If you find an error in one of our books, like a spelling mistake or faultypiece of code, we would be very grateful for your feedback By sending in errata you may save anotherreader hours of frustration and at the same time you will be helping us provide even higher qualityinformation
To find the errata page for this book, go to http://www.wrox.comand locate the title using the Searchbox or one of the title lists Then, on the book details page, click the Book Errata link On this page youcan view all errata that has been submitted for this book and posted by Wrox editors A complete booklist including links to each book’s errata is also available at www.wrox.com/misc-pages/booklist.shtml
Boxes like this one hold important, not-to-be forgotten information that is directly
relevant to the surrounding text.
Introduction
xxii
Trang 24If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtmland complete the form there to send us the error you have found We’ll check the informationand, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions
of the book
p2p.wrox.com
For author and peer discussion, join the P2P forums at p2p.wrox.com The forums are a Web-based tem for you to post messages relating to Wrox books and related technologies and interact with otherreaders and technology users The forums offer a subscription feature to e-mail you topics of interest ofyour choosing when new posts are made to the forums Wrox authors, editors, other industry experts,and your fellow readers are present on these forums
sys-At http://p2p.wrox.comyou will find a number of different forums that will help you not only asyou read this book, but also as you develop your own applications To join the forums, just follow thesesteps:
1. Go to p2p.wrox.comand click the Register link
2. Read the terms of use and click Agree
3. Complete the required information to join as well as any optional information you wish to vide and click Submit
pro-4. You will receive an e-mail with information describing how to verify your account and plete the joining process
com-You can read messages in the forums without joining P2P but in order to post your own messages, you must join.
Once you join, you can post new messages and respond to messages other users post You can read sages at any time on the Web If you would like to have new messages from a particular forum e-mailed
mes-to you, click the Subscribe mes-to this Forum icon by the forum name in the forum listing
For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to tions about how the forum software works as well as many common questions specific to P2P and Wroxbooks To read the FAQs, click the FAQ link on any P2P page
ques-Introduction
xxiii
Trang 26Professional ASP.NET 2.0 XML
Trang 28Introduction to XML
Extensible Markup Language (XML) is a language defined by the World Wide Web Consortium(W3C, http://www.w3c.org), the body that sets the standards for the Web You can use XML tocreate your own elements, thus creating a customized markup language for your own use Inthis way, XML supersedes other markup languages such as Hypertext Markup Language(HTML); in HTML, all the elements you use are predefined — and there are not enough of them
In fact, XML is a metamarkup language because it lets you create your own markup languages.XML is the next logical step in developing the full potential of the Internet and the Web Just asHTML, HyperText Transfer Protocol (HTTP), and Web browsers paved the way for exciting newmethods of communications between networked computers and people, XML and its associatedtechnologies open new avenues of electronic communications between people and machines In thecase of XML, however, the promise is for both human-machine and machine-machine communica-tions, with XML as the “lowest-common-denominator” language that all other systems — propri-etary or open — can use
XML derives much of its strength in combination with the Web The Web provides a collection ofprotocols for moving data; XML represents a way to define that data The most immediate effecthas been a new way to look at the enterprise Instead of a tightly knit network of servers, theenterprise is now seen as encompassing not just our traditional networks but also the Web itself,with its global reach and scope XML has become the unquestionable standard for genericallymarking data to be shared As XML continues to grow in popularity, so too are the number ofways in which XML is being implemented XML can be used for a variety of purposes, from obvioustasks such as marking up simple data files and storing temporary data to more complex tasks such
as passing information from one program or process to another
XML finds several applications in business and, increasingly, in everyday life It provides a commondata format for companies that want to exchange documents It’s used by Web services to encodemessages and data in a platform-independent manner It’s even used to build Web sites, where itserves as a tool for cleanly separating content from appearance
Trang 29This chapter is about XML as a language and its related technologies A comprehensive treatment ofthe subject could easily fill 300 pages or more, so this chapter attempts to strike a reasonable balancebetween detail and succinctness In the pages that follow, you learn about the different XML-relatedtechnologies and their usage But before that, take a brief look at XML itself.
A Primer on XML
XML is derived from the Standard Generalized Markup Language (SGML), a rich language used mostlyfor huge documentation projects The designers of XML drew heavily from SGML and were guided bythe lessons learned from HTML They produced a specification that was only about 20 percent the size
of the SGML specification, but nearly as powerful Although SGML is typically used by those who needthe power of an industrial-strength language, XML is intended for everyone
One of the great strengths of XML is the extensibility it brings to the table XML doesn’t have any tags of itsown and it doesn’t constrain you like other markup languages Instead, XML defines rules for developingsemantic tags of your own The tags you create form vocabularies that can be used to structure data intohierarchical trees of information You can think of XML as a metamarkup language that enables developers,companies, and even industries to create their own, specific markup languages
One of the most important concepts to grasp in XML is about content, not presentation The tags you create focus on organizing your data rather than displaying it XML isn’t used, for example, to indicate aparticular part of a document in a new paragraph or that another part should be bolded XML is used todevelop tags that indicate a particular piece of data is the author’s first name, another piece is the booktitle, and a third piece is the published year of the book
Self-Describing Data
As mentioned before, the most powerful feature of XML is that it doesn’t define any tags Creating yourown tags is what makes XML extensible; however, defining meaningful tags is up to you When creatingtags, it isn’t necessary to abbreviate or shorten your tag names It doesn’t make processing them anyfaster but it can make your XML documents more confusing or easier to understand Remember, devel-opers are going to be writing code against your XML documents On the one hand, you could certainlydefine tags like the following:
Trang 30The second example is far more readable in human terms, and it also provides more functionality andversatility to nonhumans With this set of tags, applications can easily access the book’s title or authorname without splitting any strings or searching for spaces And, for developers writing code, searchingfor the author name in an XML document becomes much more natural when the name of the element istitle, for example, rather than H1
Indenting the tags in the previous example was done purely for readability and certainly isn’t necessary
in your XML documents You may find, however, when you create your own documents, indentation helps you to read them.
To process the previous XML data, no special editors are needed to create XML documents, although anumber of them are available And no breakthrough technology is involved Much of the attentionswirling around XML comes from its simplicity Specifically, interest in XML has grown because of theway XML simplifies the tasks of the developers who employ it in their designs Many of the tough taskssoftware developers have to do again and again over the years are now much easier to accomplish XMLalso makes it easier for components to communicate with each other because it provides a standardized,structured language recognized by the most popular platforms today In fact, in the NET platform,Microsoft has demonstrated how important XML is by using it as the underpinning of the entire platform
As you see in later chapters, NET relies heavily on XML and SOAP (Simple Object Access Protocol) in itsframework and base services to make development easier and more efficient
❑ The document contains one or more elements
❑ The document consists of exactly one root element (also known as the document element)
❑ The name of an element’s end tag matches the name defined in the start tag
❑ No attribute may appear more than once within an element
❑ Attribute values cannot contain a left-angle bracket (<)
❑ Elements delimited with start and end tags must nest properly within each other
Validity
First and foremost, a valid XML document must be well-formed before it can even think about being avalid XML document The well-formed requirement should be fairly straightforward, but the key thatmakes an XML document leap from well-formed to valid is slightly more difficult To be valid, an XMLdocument must be validated A document can be validated through a Document Type Definition (DTD), or
an XML Schema Definition (XSD) For the XML document to be valid, it must conform to the constraintsexpressed by the associated DTD or the XSD schema
3
Introduction to XML