Professional ASP.NET 2.0 XML phần 3 potx

60 292 0
Professional ASP.NET 2.0 XML phần 3 potx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

} } </script> <html xmlns=”http://www.w3.org/1999/xhtml” > <head runat=”server”> <title>Writing XML File</title> </head> <body> <form id=”form1” runat=”server”> <div> <asp:label id=”lblResult” runat=”server” /> </div> </form> </body> </html> Listing 4-8 uses “urn:employees-wrox” as the namespace and the namespace prefix used is “emp”. If you navigate to the code Listing 4-8 in a browser, you will see the output shown in Figure 4-6. Figure 4-6 In Listing 4-8, you supplied the namespace as an argument to the WriteStartElement as shown in the following code. writer.WriteStartElement(“employee”, “urn:employees-wrox”); You can also accomplish this effect using the following two lines of code as well. string prefix = writer.LookupPrefix(“urn:employees-wrox”); writer.WriteStartElement(prefix, “employee”, null); 94 Chapter 4 07_596772 ch04.qxd 12/13/05 11:23 PM Page 94 By leveraging the LookupPrefix() method, you can get reference to the namespace space prefix in a local variable and then supply it as an argument to methods such as WriteStartElement(). The advantage to this approach is that you don’t have to supply the namespace to each of the creation methods; you simply supply the prefix obtained through the LookupPrefix() method to the creation methods. Writing Images Using XmlWriter The techniques described in the previous sections can also be used with any sort of binary data that can be expressed with an array of bytes, including images. This section provides you with an example and demonstrates how to embed a JPEG image in an XML document. The structure of the sample XML document is extremely simple. It consists of a single employee node, and inside that node there is an image node holding the binary image data plus an attribute containing the original file name. Code required for implementing this is shown in Listing 4-9. Listing 4-9: Embedding an Image in an XML Document <%@ Page Language=”C#” %> <%@ Import Namespace=”System.Xml” %> <%@ Import Namespace=”System.IO” %> <script runat=”server”> void Page_Load(object sender, EventArgs e) { string xmlFilePath = @”C:\Data\Employees.xml”; string imageFileName = @”C:\Data\Employee.jpg”; try { using (XmlWriter writer = XmlWriter.Create(xmlFilePath)) { //Start writing the XML document writer.WriteStartDocument(false); writer.WriteStartElement(“employee”); writer.WriteAttributeString(“id”, “1”); writer.WriteStartElement(“image”); writer.WriteAttributeString(“fileName”, imageFileName); //Get the size of the file FileInfo fi = new FileInfo(imageFileName); int size = (int)fi.Length; //Read the JPEG file byte[] imgBytes = new byte[size]; FileStream stream = new FileStream(imageFileName, FileMode.Open); BinaryReader reader = new BinaryReader(stream); imgBytes = reader.ReadBytes(size); reader.Close(); //Write the JPEG data writer.WriteBinHex(imgBytes, 0, size); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); //flush the object and write the XML data to the file writer.Flush(); lblResult.Text = “File is written successfully”; } } catch (Exception ex) { 95 Reading and Writing XML Data Using XmlReader and XmlWriter 07_596772 ch04.qxd 12/13/05 11:23 PM Page 95 lblResult.Text = “An Exception occurred: “ + ex.Message; } } </script> <html xmlns=”http://www.w3.org/1999/xhtml” > <head runat=”server”> <title>Writing Images using XmlWriter</title> </head> <body> <form id=”form1” runat=”server”> <div> <asp:label id=”lblResult” runat=”server” /> </div> </form> </body> </html> Listing 4-9 uses the FileInfo class to determine the size of the JPEG file. FileInfo is a helper class in the System.IO namespace that allows you to retrieve information about individual files. The contents of the employees.jpeg file are extracted using the ReadBytes method of the .NET binary reader. The contents are then encoded as BinHex and written to the XML document. Figure 4-7 shows the output produced by the code. Figure 4-7 Summary This chapter introduced you to .NET’s XML-handling capabilities. The .NET architecture provides the most complete, integrated support platform for XML yet from Microsoft, and it makes many otherwise daunting tasks much easier to accomplish. This chapter introduced you to the SAX and DOM methods for processing XML, and showed you how the Microsoft approach attempts to marry these two approaches using a model that provides the benefits of both. 96 Chapter 4 07_596772 ch04.qxd 12/13/05 11:23 PM Page 96 Specifically, you learned how to read XML using the XmlReader class, and how to use the XmlReaderSettings object in conjunction with the XmlReader object to customize the output of the XmlReader object. You learned how to use the XmlWriter class to write XML data files, which greatly reduces the amount of information that an application has to keep track of when writing XML. Finally, you learned how to use the XmlWriter object to create namespaces and embed images in an XML Document. As you can see, after you know the basics of reading an XML file with the XmlReader, it’s very easy to begin using its built-in constructs to extract and manipulate XML data to your precise needs. Hopefully this chapter gave you the motivation to start writing your own XML applications. XML is clearly going to play a large role in future Web development, and learning these skills is essential to the success of any Web application developer. As an exercise to better understand how this works, I recommend taking your own XML markup and writing a similar script to extract element and attribute values from it. After all, practice makes perfect! 97 Reading and Writing XML Data Using XmlReader and XmlWriter 07_596772 ch04.qxd 12/13/05 11:23 PM Page 97 07_596772 ch04.qxd 12/13/05 11:23 PM Page 98 XML Data Validation In the previous chapters, you have seen all about reading XML files, and even checking if they are well-formed and valid. This chapter takes a step into more advanced territory by looking at how to perform validation of XML data at the time of reading XML data. This chapter discusses the dif- ferent types of XML validation using the classes in the System.Xml namespace. This chapter also provides an in-depth discussion on the .NET Schema Object Model by providing examples on how to programmatically create and read XML schemas. Specifically, this chapter will cover: ❑ XML validation support provided by the .NET Framework 2.0 ❑ How to validate an XML file using the XmlReaderSettings class in conjunction with the XmlReader class ❑ How to take advantage of the XmlSchemaSet class to cache XML schemas and then use them to validate XML files ❑ How to perform XML DOM validation through the XmlNodeReader class ❑ How to use inline schemas to validate XML data ❑ How to validate XML data using DTDs ❑ Visual Studio’s support for creating XSD schemas ❑ How to programmatically read XSD schemas using XmlSchema ❑ How to programmatically create XSD schemas ❑ How to programmatically infer XSD schema from an XML file The next section starts by reviewing the validation support provided by the .NET Framework 2.0. 08_596772 ch05.qxd 12/13/05 11:17 PM Page 99 XML Validation Validation is the process of enforcing rules on the XML content either via a XSD schema or a DTD or a XDR schema. There are two ways to define a structure for an XML document, sometimes called a vocabulary: DTDs and XML schemas. Using an XML schema is a newer and somewhat more flexible technique than using a DTD, but both approaches are in common use. A DTD or schema may be embedded within an XML file, but more often it will be contained in a separate file. An XML processing program, called a parser, can check an XML document against its DTD or schema to see if it follows the rules; this process is called validation. An XML file that follows all the rules in its DTD or schema is said to be valid. The XML schema file usually is an XML-Data Reduced (XDR) or XML Schema Definition language (XSD) file. XSD schema-based validation is the industry accepted standard and is the primary method of XML validation used in most of the applications. Although validation of XML data using DTDs is used only in legacy applications, this chapter provides you with an example on how to use DTDs for XML validation. Validation Types Supported in .NET Framework 2.0 In .NET Framework, there are a number of ways you can perform validation of XML data. Before dis- cussing those validation types, it is important to understand the key differences between the validation mechanisms (DTD, XDR, and XSD) supported by the .NET Framework. ❑ DTD —A text file whose syntax stems directly from the Standard Generalized Markup Language (SGML) —the ancestor of XML as we know it today. A DTD follows a custom, non- XML syntax to define the set of valid tags, the attributes each tag can support, and the depen- dencies between tags. A DTD allows you to specify the children for each tag, their cardinality, their attributes, and a few other properties for both tags and attributes. Cardinality specifies the number of occurrences of each child element. ❑ XDR —A schema language based on a proposal submitted by Microsoft to the W3C back in 1998. (For more information, see http://www.w3.org/TR/1998/NOTE-XML-data-0105.) XDRs are flexible and overcome some of the limitations of DTDs. Unlike DTDs, XDRs describe the structure of the document using the same syntax as the XML document. Additionally, in a DTD, all the data content is character data. XDR language schemas allow you to specify the data type of an element or an attribute. Note that XDR never reached the recommendation status. ❑ XSD —Defines the elements and attributes that form an XML document. Each element is strongly typed. Based on a W3C recommendation, XSD describes the structure of XML docu- ments using another XML document. XSDs include an all-encompassing type system composed of primitive and derived types. The XSD type system is also at the foundation of the Simple Object Access Protocol (SOAP) and XML Web services. As mentioned, XDR is an early hybrid specification that never reached the status of a W3C recommendation since it evolved into XSD. The .NET classes support XDR mostly for backward compatibility; however XDR is fully supported by the Component Object Model (COM)-based Microsoft XML Core Services (MSXML) parser. 100 Chapter 5 08_596772 ch05.qxd 12/13/05 11:17 PM Page 100 The .NET Framework provides a handy utility, named xsd.exe, that among other things can automatically convert an XDR schema to XSD. If you pass an XDR schema file (typically, an .xdr extension), xsd.exe converts the XDR schema to an XSD schema, as shown here: xsd.exe Authors.xdr The output file has the same name as the XDR schema, but with the .xsd extension. XML Data Validation Using XSD Schemas An XML document contains elements, attributes, and values of primitive data types. Throughout this chapter, I will use an XML document named Authors.xml, which is shown in Listing 5-1. Listing 5-1: Authors.xml File <?xml version=”1.0”?> <authors> <author> <au_id>172-32-1176</au_id> <au_lname>White</au_lname> <au_fname>Johnson</au_fname> <phone>408 496-7223</phone> <address>10932 Bigge Rd.</address> <city>Menlo Park</city> <state>CA</state> <zip>94025</zip> <contract>true</contract> </author> <author> <au_id>213-46-8915</au_id> <au_lname>Green</au_lname> <au_fname>Marjorie</au_fname> <phone>415 986-7020</phone> <address>309 63rd St. #411</address> <city>Oakland</city> <state>CA</state> <zip>94618</zip> <contract>true</contract> </author> </authors> XSD schema defines elements, attributes, and the relationship between them. It conforms to the W3C XML schema standards and recommendations. XSD schema for the Authors.xml document is Authors.xsd, and that is shown in Listing 5-2. DTD was considered the cross-platform standard until a few years ago. The W3C then officialized a newer standard— XSD— which is, technically speaking, far superior to DTD. Today, XSD is supported by almost all parsers on all platforms. Although the support for DTD will not be deprecated anytime soon, you’ll be better positioned if you start migrating to XSD or building new XML-driven applications based on XSD instead of DTD or XDR. 101 XML Data Validation 08_596772 ch05.qxd 12/13/05 11:17 PM Page 101 Listing 5-2: Authors.xsd File <?xml version=”1.0” encoding=”utf-8”?> <xs:schema attributeFormDefault=”unqualified” elementFormDefault=”qualified” xmlns:xs=”http://www.w3.org/2001/XMLSchema”> <xs:element name=”authors”> <xs:complexType> <xs:sequence> <xs:element maxOccurs=”unbounded” name=”author”> <xs:complexType> <xs:sequence> <xs:element name=”au_id” type=”xs:string” /> <xs:element name=”au_lname” type=”xs:string” /> <xs:element name=”au_fname” type=”xs:string” /> <xs:element name=”phone” type=”xs:string” /> <xs:element name=”address” type=”xs:string” /> <xs:element name=”city” type=”xs:string” /> <xs:element name=”state” type=”xs:string” /> <xs:element name=”zip” type=”xs:unsignedInt” /> <xs:element name=”contract” type=”xs:boolean” /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> .NET Framework 2.0 classes support the W3C XML schema recommendation. The classes that are commonly employed to validate the XML document are XmlReader, XmlReaderSettings, XmlSchemaSet, and XmlNodeReader. The sequence of steps to validate an XML document using an XSD schema is as follows. Steps for Validating an XML Document ❑ A ValidationEventHandler event handler method is defined. ❑ An instance of the XmlReaderSettings object is created. XmlReaderSettings class allows you to specify a set of options that will be supported on the XmlReader object and these options will be in effect when parsing XML data. Note that the XmlReaderSettings renders the XmlValidatingReader class (used with .NET 1.x version) obsolete. ❑ The previously defined ValidationEventHandler method is associated with the XmlReaderSettings class. ❑ The ValidationType property of the XmlReaderSettings is set to ValidationType.Schema. ❑ An XSD schema is added to the XmlReaderSettings class through the Schemas property of the XmlReaderSettings class. ❑ The XmlReader class validates the XML document while parsing the XML data using the Read method. 102 Chapter 5 08_596772 ch05.qxd 12/13/05 11:17 PM Page 102 Validation Event Handler The ValidationEventHandler event is used to define an event handler for receiving the notification about XSD schema validation errors. The validation errors and warnings are reported through the ValidationEventHandler call-back function. Validation errors do not stop parsing and parsing only stops if the XML document is not well-formed. If you do not provide validation event handler callback function and a validation error occurs, however, an exception is thrown. This approach of using the validation event callback mechanism to trap all validation errors enables all validation errors to be discovered in a single pass. Role of XmlReaderSettings Class in XML Validation The XmlReaderSettings class is one of the most important classes along with the XmlReader class that provides the core foundation for validating XML data. Table 5-1 provides a brief recap of the validation related properties of the XmlReaderSettings class that will be utilized later in this chapter. Table 5-1. Validation Related Properties and Events of XmlReaderSettings Class Property Description ProhibitDtd Indicates if the DTD validation is supported in the XmlRead- erSettings class. The default value is true meaning that the DTD validation is not supported. ValidationType Specifies the type of validation supported on the XmlReader- Settings class. The permitted validation types are DTD, XSD, and None. ValidationEventHandler Specifies an event handler that will receive information about validation events. ValidationFlags Specifies additional validation settings such as use of inline schemas, identity constraints, and XML attributes that will be enforced when validating the XML data. Schemas Gets or sets the XmlSchemaSet object that represents the collection of schemas to be used for performing schema validation. To validate XML data using the XmlReaderSettings class, you need to set the properties of the XmlReaderSettings class to appropriate values. This class does not operate on its own, but works in conjunction with an XmlReader or XmlNodeReader instance. You can use this class to validate against either a DTD or an XML schema. An XML Validation Example Now that you have a general understanding of the steps involved in validating XML data, it is time to look at an example to understand how it actually works. Listing 5-3 utilizes the Authors.xsd schema file to validate the Authors.xml file. 103 XML Data Validation 08_596772 ch05.qxd 12/13/05 11:17 PM Page 103 [...]... the XmlDocument object into an XmlNodeReader object, the Authors .xml file is loaded into an XmlDocument and modified in-memory by adding an attribute called “test” XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlPath); XmlElement authorElement = (XmlElement) xmlDoc.DocumentElement.SelectSingleNode (“//authors/author[au_id=’172 -32 -1176’]”); authorElement.SetAttribute(“test”, “test”); The XML. .. e) { string xmlPath = Request.PhysicalApplicationPath + @”\App_Data\Authors .xml ; string xsdPath = Request.PhysicalApplicationPath + @”\App_Data\Authors.xsd”; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlPath); XmlElement authorElement = (XmlElement) xmlDoc.DocumentElement.SelectSingleNode (“//authors/author[au_id=’172 -32 -1176’]”); authorElement.SetAttribute(“test”, “test”); XmlNodeReader... ns); XmlSchemaElement phone = new XmlSchemaElement(); phone.Name = “phone”; phone.SchemaTypeName = new XmlQualifiedName(“string”, ns); XmlSchemaElement address = new XmlSchemaElement(); address.Name = “address”; address.SchemaTypeName = new XmlQualifiedName(“string”, ns); XmlSchemaElement city = new XmlSchemaElement(); city.Name = “city”; city.SchemaTypeName = new XmlQualifiedName(“string”, ns); XmlSchemaElement... the XmlSchemaSet Remove Removes the specified XSD schema from the XmlSchemaSet Reprocess Reprocesses an XSD schema that already exists in the XmlSchemaSet Listing 5-4 shows you an example of how to utilize the XmlSchemaSet class for validating XML data Listing 5-4: Validating XML Data Using XmlSchemaSet Class . XmlWriter 07 _5967 72 ch04.qxd 12/ 13 /05 11 : 23 PM Page 97 07 _5967 72 ch04.qxd 12/ 13 /05 11 : 23 PM Page 98 XML Data Validation In the previous chapters, you have seen all about reading XML files, and even. of the XmlReaderSettings class. ❑ The XmlReader class validates the XML document while parsing the XML data using the Read method. 1 02 Chapter 5 08 _5967 72 ch05.qxd 12/ 13 /05 11:17 PM Page 1 02 Validation. the Component Object Model (COM)-based Microsoft XML Core Services (MSXML) parser. 100 Chapter 5 08 _5967 72 ch05.qxd 12/ 13 /05 11:17 PM Page 100 The .NET Framework provides a handy utility, named

Ngày đăng: 12/08/2014, 23:22

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan