Professional Visual Basic 2010 and .neT 4 phần 4 docx

133 398 0
Professional Visual Basic 2010 and .neT 4 phần 4 docx

Đ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

356 ❘ CHAPTER 9 usiNG xml witH Visual BasiC In this case, the XmlReader object that is created ignores the white space that it encounters, as well as any of the XML comments. These settings, once established with the XmlReaderSettings object, are then associated with the XmlReader object through its Create method. Traversing XML Using XmlReader An application can easily use XmlReader to traverse a document that is received in a known format. The document can thus be traversed in a deliberate manner. You just implemented a class that serialized arrays of movie orders. The next example takes an XML document containing multiple XML documents of that type and traverses them. Each movie order is forwarded to the movie supplier via fax. The document is traversed as follows: Read root element: <MovieOrderDump> Process each <FilmOrderList> element Read <multiFilmOrders> element Process each <FilmOrder> Send fax for each movie order here The basic outline for the program’s implementation is to open a file containing the XML document to parse and to traverse it from element to element: Dim myXmlSettings As New XmlReaderSettings() Using readMovieInfo As XmlReader = XmlReader.Create(fileName, myXmlSettings) readMovieInfo.Read() readMovieInfo.ReadStartElement("MovieOrderDump") Do While (True) '**************************************************** '* Process FilmOrder elements here * '**************************************************** Loop readMovieInfo.ReadEndElement() ' </MovieOrderDump> End Using Code snippet from FilmOrdersReader2 The preceding code opened the file using the constructor of XmlReader, and the End Using statement takes care of shutting everything down for you. The code also introduced two methods of the XmlReader class: ➤ ReadStartElement(String) — This verifies that the current node in the stream is an element and that the element’s name matches the string passed to ReadStartElement. If the verification is successful, then the stream is advanced to the next element. ➤ ReadEndElement() — This verifies that the current element is an end tab; and if the verification is successful, then the stream is advanced to the next element. The application knows that an element, <MovieOrderDump>, will be found at a specific point in the document. The ReadStartElement method verifies this foreknowledge of the document format. After all the elements contained in element <MovieOrderDump> have been traversed, the stream should point to the end tag </MovieOrderDump>. The ReadEndElement method verifies this. The code that traverses each element of type <FilmOrder> similarly uses the ReadStartElement and ReadEndElement methods to indicate the start and end of the <FilmOrder> and <multiFilmOrders> elements. The code that ultimately parses the list of movie orders and then faxes the movie supplier (using the FranticallyFaxTheMovieSupplier subroutine) is as follows: Private Sub ReadMovieXml(ByVal fileName As String) Dim myXmlSettings As New XmlReaderSettings() Dim movieName As String Dim movieId As String Dim quantity As String XmlReader.Create(fileName, myXmlSettings) Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 'position to first element readMovieInfo.Read() readMovieInfo.ReadStartElement("MovieOrderDump") Do While (True) readMovieInfo.ReadStartElement("FilmOrderList") readMovieInfo.ReadStartElement("multiFilmOrders") 'for each order Do While (True) readMovieInfo.MoveToContent() movieId = readMovieInfo.GetAttribute("filmId") readMovieInfo.ReadStartElement("FilmOrder") movieName = readMovieInfo.ReadElementString() quantity = readMovieInfo.ReadElementString() readMovieInfo.ReadEndElement() ' clear </FilmOrder> FranticallyFaxTheMovieSupplier(movieName, movieId, quantity) ' Should read next FilmOrder node ' else quits readMovieInfo.Read() If ("FilmOrder" <> readMovieInfo.Name) Then Exit Do End If Loop readMovieInfo.ReadEndElement() ' clear </multiFilmOrders> readMovieInfo.ReadEndElement() ' clear </FilmOrderList> ' Should read next FilmOrderList node ' else you quit readMovieInfo.Read() ' clear </MovieOrderDump> If ("FilmOrderList" <> readMovieInfo.Name) Then Exit Do End If Loop readMovieInfo.ReadEndElement() ' </MovieOrderDump> End Using End Sub Code snippet from FilmOrderReader2 The values are read from the XML file using the ReadElementString and GetAttribute methods. Notice that the call to GetAttribute is done before reading the FilmOrder element. This is because the ReadStartElement method advances the location for the next read to the next element in the XML file. The MoveToContent call before the call to GetAttribute ensures that the current read location is on the element, and not on white space. While parsing the stream, it was known that an element named name existed and that this element contained the name of the movie. Rather than parse the start tag, get the value, and parse the end tag, it was easier to get the data using the ReadElementString method. The output of this example is a fax (left as an exercise for you). The format of the document is still verified by XmlReader as it is parsed. The XmlReader class also exposes properties that provide more insight into the data contained in the XML document and the state of parsing: IsEmptyElement, EOF, HasAttributes, and IsStartElement. .NET CLR-compliant types are not 100 percent interchangeable with XML types, so ever since the .NET Framework 2.0 was introduced, the new methods it made available in the XmlReader make the process of casting from one of these XML types to .NET types easier. XML Stream-Style Parsers ❘ 357 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 358 ❘ CHAPTER 9 usiNG xml witH Visual BasiC Using the ReadElementContentAs method, you can easily perform the necessary casting required: Dim username As String = _ myXmlReader.ReadElementContentAs(GetType(String), DBNull.Value) Dim myDate As DateTime = _ myXmlReader.ReadElementContentAs(GetType(DateTime), DBNull.Value) In addition to the generic ReadElementContentAs method, there are specific ReadElementContentAsX methods for each of the common data types; and in addition to these methods, the raw XML associated with the document can also be retrieved, using ReadInnerXml and ReadOuterXml. Again, this only scratches the surface of the XmlReader class, a class quite rich in functionality. Handling Exceptions XML is text and could easily be read using mundane methods such as Read and ReadLine. A key feature of each class that reads and traverses XML is inherent support for error detection and handling. To demonstrate this, consider the following malformed XML document found in the file named Malformed.xml: <?xml version="1.0" encoding="IBM437" ?> <FilmOrder FilmId="101", Qty="10"> <Name>Grease</Name> <FilmOrder> Code snippet from FilmOrdersReader2 This document may not immediately appear to be malformed. By wrapping a call to the method you developed (ReadMovieXml), you can see what type of exception is raised when XmlReader detects the malformed XML within this document as shown in Sub Main(). Comment out the line calling the MovieManage.xml file, and uncomment the line to try to open the malformed.xml file: Try 'ReadMovieXml("MovieManage.xml") ReadMovieXml("Malformed.xml") Catch xmlEx As XmlException Console.Error.WriteLine("XML Error: " + xmlEx.ToString()) Catch ex As Exception Console.Error.WriteLine("Some other error: " + ex.ToString()) End Try Code snippet from FilmOrdersReader2 The methods and properties exposed by the XmlReader class raise exceptions of type System.Xml .XmlException . In fact, every class in the System.Xml namespace raises exceptions of type XmlException. Although this is a discussion of errors using an instance of type XmlReader, the concepts reviewed apply to all errors generated by classes found in the System.Xml namespace. The XmlException extends the basic Exception to include more information about the location of the error within the XML file. The error displayed when subroutine ReadMovieXML processes Malformed.xml is as follows: XML Error: System.Xml.XmlException: The ',' character, hexadecimal value 0x2C, cannot begin a name. Line 2, position 49. The preceding snippet indicates that a comma separates the attributes in element <FilmOrder FilmId=“101”, Qty=“10“>. This comma is invalid. Removing it and running the code again results in the following output: XML Error: System.Xml.XmlException: This is an unexpected token. Expected 'EndElement'. Line 5, position 27. Again, you can recognize the precise error. In this case, you do not have an end element, </FilmOrder>, but you do have an opening element, <FilmOrder>. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com The properties provided by the XmlException class (such as LineNumber, LinePosition, and Message) provide a useful level of precision when tracking down errors. The XmlReader class also exposes a level of precision with respect to the parsing of the XML document. This precision is exposed by the XmlReader through properties such as LineNumber and LinePosition. Document Object Model (DOM) The Document Object Model (DOM) is a logical view of an XML file. Within the DOM, an XML document is contained in a class named XmlDocument. Each node within this document is accessible and managed using XmlNode. Nodes can also be accessed and managed using a class specifically designed to process a specific node’s type (XmlElement, XmlAttribute, and so on). XML documents are extracted from XmlDocument using a variety of mechanisms exposed through such classes as XmlWriter, TextWriter, Stream, and a file (specified by a filename of type String). XML documents are consumed by an XmlDocument using a variety of load mechanisms exposed through the same classes. A DOM-style parser differs from a stream-style parser with respect to movement. Using the DOM, the nodes can be traversed forward and backward; and nodes can be added to the document, removed from the document, and updated. However, this flexibility comes at a performance cost. It is faster to read or write XML using a stream-style parser. The DOM-specific classes exposed by System.Xml include the following: ➤ XmlDocument — Corresponds to an entire XML document. A document is loaded using the Load or LoadXml methods. The Load method loads the XML from a file (the filename specified as type String), TextReader, or XmlReader. A document can be loaded using LoadXml in conjunction with a string containing the XML document. The Save method is used to save XML documents. The methods exposed by XmlDocument reflect the intricate manipulation of an XML document. For example, the following creation methods are implemented by this class: CreateAttribute, CreateCDataSection, CreateComment, CreateDocumentFragment, CreateDocumentType, CreateElement, CreateEntityReference, CreateNavigator, CreateNode, CreateProcessingInstruction, CreateSignificantWhitespace, CreateTextNode, CreateWhitespace, and CreateXmlDeclaration. The elements contained in the document can be retrieved. Other methods support the retrieving, importing, cloning, loading, and writing of nodes. ➤ XmlNode — Corresponds to a node within the DOM tree. This is the base class for the other node type classes. A robust set of methods and properties is provided to create, delete, and replace nodes. The contents of a node can similarly be traversed in a variety of ways: FirstChild, LastChild, NextSibling, ParentNode, and PreviousSibling. ➤ XmlElement — Corresponds to an element within the DOM tree. The functionality exposed by this class contains a variety of methods used to manipulate an element’s attributes. ➤ XmlAttribute — Corresponds to an attribute of an element (XmlElement) within the DOM tree. An attribute contains data and lists of subordinate data, so it is a less complicated object than an XmlNode or an XmlElement. An XmlAttribute can retrieve its owner document (property, OwnerDocument), retrieve its owner element (property, OwnerElement), retrieve its parent node (property, ParentNode), and retrieve its name (property, Name). The value of an XmlAttribute is available via a read-write property named Value. Given the diverse number of methods and properties exposed by XmlDocument, XmlNode, XmlElement, and XmlAttribute (and there are many more than those listed here), it’s clear that any XML 1.0 or 1.1-compliant document can be generated and manipulated using these classes. In comparison to their XML stream counterparts, these classes offer more flexible movement within the XML document and through any editing of XML documents. A similar comparison could be made between DOM and data serialized and deserialized using XML. Using serialization, the type of node (for example, attribute or element) and the node name are specified at compile time. There is no on-the-fly modification of the XML generated by the serialization process. XML Stream-Style Parsers ❘ 359 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 360 ❘ CHAPTER 9 usiNG xml witH Visual BasiC DOM Traversing XML The first DOM example loads an XML document into an XmlDocument object using a string that contains the actual XML document. The example over the next few pages simply traverses each XML element (XmlNode) in the document (XmlDocument) and displays the data to the console. The data associated with this example is contained in a variable, rawData, which is initialized as follows: Dim rawData = <multiFilmOrders> <FilmOrder> <name>Grease</name> <filmId>101</filmId> <quantity>10</quantity> </FilmOrder> <FilmOrder> <name>Lawrence of Arabia</name> <filmId>102</filmId> <quantity>10</quantity> </FilmOrder> </multiFilmOrders> Code snippet from DomReading The XML document in rawData is a portion of the XML hierarchy associated with a movie order. Notice the lack of quotation marks around the XML: This is an XML literal. XML literals allow you to insert a block of XML directly into your VB source code. They can be written over a number of lines, and can be used wherever you might normally load an XML file. The basic idea in processing this data is to traverse each <FilmOrder> element in order to display the data it contains. Each node corresponding to a <FilmOrder> element can be retrieved from your XmlDocument using the GetElementsByTagName method (specifying a tag name of FilmOrder). The GetElementsByTagName method returns a list of XmlNode objects in the form of a collection of type XmlNodeList. Using the For Each statement to construct this list, the XmlNodeList (movieOrderNodes) can be traversed as individual XmlNode elements (movieOrderNode). The code for handling this is as follows: Dim xmlDoc As New XmlDocument Dim movieOrderNodes As XmlNodeList Dim movieOrderNode As XmlNode xmlDoc.LoadXml(rawData.ToString()) ' Traverse each <FilmOrder> movieOrderNodes = xmlDoc.GetElementsByTagName("FilmOrder") For Each movieOrderNode In movieOrderNodes '********************************************************** ' Process <name>, <filmId> and <quantity> here '********************************************************** Next Code snippet from DomReading Each XmlNode can then have its contents displayed by traversing the children of this node using the ChildNodes method. This method returns an XmlNodeList (baseDataNodes) that can be traversed one XmlNode list element at a time: Dim baseDataNodes As XmlNodeList Dim bFirstInRow As Boolean baseDataNodes = movieOrderNode.ChildNodes bFirstInRow = True For Each baseDataNode As XmlNode In baseDataNodes If (bFirstInRow) Then bFirstInRow = False Else Console.Write(", ") Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com End If Console.Write(baseDataNode.Name & ": " & baseDataNode.InnerText) Next Console.WriteLine() Code snippet from DomReading The bulk of the preceding code retrieves the name of the node using the Name property and the InnerText property of the node. The InnerText property of each XmlNode retrieved contains the data associated with the XML elements (nodes) <name>, <filmId>, and <quantity>. The example displays the contents of the XML elements using Console.Write. The XML document is displayed to the console as follows: name: Grease, quantity: 10 name: Lawrence of Arabia, quantity: 10 Other, more practical, methods for using this data could have been implemented, including the following: The contents could have been directed to an ASP.NET ➤ Response object, and the data retrieved could have been used to create an HTML table ( <table> table, <tr> row, and <td> data) that would be written to the Response object. The data traversed could have been directed to a ➤ ListBox or ComboBox Windows Forms control. This would enable the data returned to be selected as part of a GUI application. The data could have been edited as part of your application’s business rules. For example, you could ➤ have used the traversal to verify that the <filmId> matched the <name>. Something like this could be done if you wanted to validate the data entered into the XML document in any manner. Writing XML with the DOM You can also use the DOM to create or edit XML documents. Creating new XML items is a two-step process, however. First, you use the containing document to create the new element, attribute, or comment (or other node type), and then you add that at the appropriate location in the document. Just as there are a number of methods in the DOM for reading the XML, there are also methods for creating new nodes. The XmlDocument class has the basic CreateNode method, as well as specific methods for creating the different node types, such as CreateElement, CreateAttribute, CreateComment, and others. Once the node is created, you add it in place using the AppendChild method of XmlNode (or one of the children of XmlNode). Create a new project that will be used to demonstrate writing XML with the DOM. Most of the work in this sample will be done in two functions, so the Main method can remain simple: Sub Main() Dim data As String Dim fileName As String = "filmorama.xml" data = GenerateXml(fileName) Console.WriteLine(data) Console.WriteLine("Press ENTER to continue") Console.ReadLine() End Sub Code snippet from DomWriting The GenerateXml function creates the initial XmlDocument, and calls the CreateFilmOrder function multiple times to add a number of items to the structure. This creates a hierarchical XML document that can then be used elsewhere in your application. Typically, you would use the Save method to write XML Stream-Style Parsers ❘ 361 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 362 ❘ CHAPTER 9 usiNG xml witH Visual BasiC the XML to a stream or document, but in this case it just retrieves the OuterXml (that is, the full XML document) to display: Private Function GenerateXml(ByVal fileName As String) As String Dim result As String Dim doc As New XmlDocument Dim elem As XmlElement 'create root node Dim root As XmlElement = doc.CreateElement("FilmOrderList") doc.AppendChild(root) 'this data would likely come from elsewhere For i As Integer = 1 To 5 elem = CreateFilmOrder(doc, i) root.AppendChild(elem) Next result = doc.OuterXml Return result End Function Code snippet from DomWriting The most common error made when writing an XML document using the DOM is to create the elements but forget to append them into the document. This step is done here with the AppendChild method, but other methods can be used, in particular InsertBefore, InsertAfter, PrependChild, and RemoveChild. Creating the individual FilmOrder nodes uses a similar CreateElement/AppendChild strategy. In addition, attributes are created using the Append method of the Attributes collection for each XmlElement: Private Function CreateFilmOrder(ByVal parent As XmlDocument, ByVal count As Integer) As XmlElement Dim result As XmlElement Dim id As XmlAttribute Dim title As XmlElement Dim quantity As XmlElement result = parent.CreateElement("FilmOrder") id = parent.CreateAttribute("id") id.Value = 100 + count title = parent.CreateElement("title") title.InnerText = "Some title here" quantity = parent.CreateElement("quantity") quantity.InnerText = "10" result.Attributes.Append(id) result.AppendChild(title) result.AppendChild(quantity) Return result End Function Code snippet from DomWriting This generates the following XML (although it will all be on one line in the output): <FilmOrderList> <FilmOrder id="101"> <title>Some title here</title> <quantity> 10 </quantity> </FilmOrder> Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com <FilmOrder id="102"> <title>Some title here</title> <quantity> 10 </quantity> </FilmOrder> <FilmOrder id="103"> <title>Some title here</title> <quantity> 10 </quantity> </FilmOrder> <FilmOrder id="104"> <title>Some title here</title> <quantity>10</quantity> </FilmOrder> <FilmOrder id="105"> <title> Some title here </title> <quantity>10</quantity> </FilmOrder> </FilmOrderList> Once you get the hang of creating XML with the DOM (and forget to add the new nodes a few dozen times), it is quite a handy method for writing XML. If the XML you need to create can all be created at once, it is probably better to use the XmlWriter class instead. Writing XML with the DOM is best left for those situations when you need to either edit an existing XML document or move backwards through the document as you are writing. In addition, because the DOM is an international standard, it means that code using the DOM is portable to other languages that also provide a DOM. In addition to the XmlWriter, the XElement shown later in this chapter provides yet another method for reading and writing XML. XSL TRANSFORMATIONS XSLT is used to transform XML documents into another format altogether. One popular use of XSLT is to transform XML into HTML so that XML documents can be presented visually. The idea is to use an alternate language (XSLT) to transform the XML, rather than rewrite the source code, SQL commands, or some other mechanism used to generate XML. Conceptually, XSLT is straightforward. A file (a .xsl file) describes the changes (transformations) that will be applied to a particular XML file. Once this is completed, an XSLT processor is provided with the source XML file and the XSLT file, and performs the transformation. The System.Xml.Xsl.XslTransform class is such an XSLT processor. Another processor you will find (introduced in the .NET Framework 2.0) is the XsltCommand object found at SystemXml.Query.XsltCommand. This section looks at using both of these processors. You can also find some features in Visual Studio that deal with XSLT. The IDE supports items such as XSLT data breakpoints and XSLT debugging. Additionally, XSLT stylesheets can be compiled into assemblies even more easily with the command-line stylesheet compiler, XSLTC.exe. The XSLT file is itself an XML document. Dozens of XSLT commands can be used in writing an XSLT file. The first example explores the following XSLT elements (commands): ➤ stylesheet — This element indicates the start of the style sheet (XSL) in the XSLT file. ➤ template — This element denotes a reusable template for producing specific output. This output is generated using a specific node type within the source document under a specific context. For example, the text <xsl: template match=“/”> selects all root nodes (“/”) for the specific transform template. The template is applied whenever the match occurs in the source document. XSL Transformations ❘ 363 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 364 ❘ CHAPTER 9 usiNG xml witH Visual BasiC ➤ for-each — This element applies the same template to each node in the specified set. Recall the example class ( FilmOrderList) that could be serialized. This class contained an array of movie orders. Given the XML document generated when a FilmOrderList is serialized, each movie order serialized could be processed using <xsl:for-each select = "FilmOrderList/multiFilmOrders/FilmOrder">. ➤ value-of — This element retrieves the value of the specified node and inserts it into the document in text form. For example, <xsl:value-of select=“name” /> would take the value of the XML element <name> and insert it into the transformed document. You can use XSLT to convert an XML document to generate a report that is viewed by the manager of the movie supplier. This report is in HTML form so that it can be viewed via the Web. The XSLT elements you previously reviewed (stylesheet, template, and for-each) are the only XSLT elements required to transform the XML document (in which data is stored) into an HTML file (data that can be displayed). An XSLT file DisplayOrders.xslt contains the following text, which is used to transform a serialized version, FilmOrderList found in Filmorama.xml: <?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <html> <head><title>What people are ordering</title> </head> <body> <table border="1"> <tr> <th> Film Name </th> <th> Film ID </th> <th> Quantity </th> </tr> <xsl:for-each select= "//FilmOrder"> <tr> <td> <xsl:value-of select="Title" /> </td> <td> <xsl:value-of select="@id" /> </td> <td> <xsl:value-of select="Quantity" /> </td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> Code snippet from Transformation Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com In the preceding XSLT fi le, the XSLT elements are marked in bold. These elements perform operations on the source XML fi le containing a serialized FilmOrderList object, and generate the appropriate HTML fi le. Your generated fi le contains a table (marked by the table tag, < table > ) that contains a set of rows (each row marked by a table row tag, < tr > ). The columns of the table are contained in table data tags, < td > . Each row containing data (an individual movie order from the serialized object, FilmOrderList ) is generated using the XSLT element, for - each , to traverse each < FilmOrder > element within the source XML document. In this case, a shorthand for the location of the FilmOrder element was used: //FilmOrder returns all FilmOrder elements, regardless of their depth in the XML fi le. Alternately, you could have specifi ed the full path using FilmOrderList / FilmOrders / FilmOrder here. The individual columns of data are generated using the value - of XSLT element, in order to query the elements contained within each < FilmOrder > element ( < Title > , < id > , and < Quantity > ) . The code in Sub Main() to create a displayable XML fi le using the XslCompiledTransform object is as follows: Dim xslt As New XslCompiledTransform Dim outputFile As String = " \ \output.html" xslt.Load(" \ \displayorders.xslt") xslt.Transform(" \ \filmorama.xml", outputFile) Process.Start(outputFile) Code snippet from Transformation This consists of only fi ve lines of code, with the bulk of the coding taking place in the XSLT fi le. The previous code snippet created an instance of a System.Xml.Xsl.XslCompiledTransform object named xslt . The Load method of this class is used to load the XSLT fi le you previously reviewed, DisplayOrders.xslt . The Transform method takes a source XML fi le as the fi rst parameter, which in this case was a fi le containing a serialized FilmOrderList object. The second parameter is the destination fi le created by the transform ( Output.html ). The Start method of the Process class is used to display the HTML fi le in the system default browser. This method launches a process that is best suited for displaying the fi le provided. Basically, the extension of the fi le dictates which application will be used to display the fi le. On a typical Windows machine, the program used to display this fi le is Internet Explorer, as shown in Figure 9 - 2. Don ’ t confuse displaying this HTML fi le with ASP.NET. Displaying an HTML fi le in this manner takes place on a single machine without the involvement of a Web server. FIGURE 9  2 As demonstrated, the backbone of the System.Xml.Xsl namespace is the XslCompiledTransform class. This class uses XSLT fi les to transform XML documents. XslCompiledTransform exposes the following methods and properties: ➤ XmlResolver — This get/set property is used to specify a class (abstract base class, XmlResolver ) that is used to handle external references (import and include elements within the style sheet). These XSL Transformations ❘ 365 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... learning how to use it in Visual Basic and the NET Framework Among other things, you also need a good understanding of XSLT, XPath, and XQuery For more details on these standards, see Professional XML from Wrox Other Classes and Interfaces in System.Xml.Xsl We just took a good look at XSLT and the System.Xml.Xsl namespace, but there is a lot more to it than that Other classes and interfaces exposed by... "USA"), New XElement("Zip", "07030-57 74" ))) Here, the attribute MyAttribute with a value of MyAttributeValue is added to the root element of the XML document, producing the results shown in Figure 9-10 Figure 9-10 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Visual Basic and XML Literals  ❘  379 Visual Basic and XML Literals Visual Basic takes LINQ to XML one step further,... ADO.NET is mentioned without a version number after it (that is, 1.x, 2.0, 3.5, or 4) , the statement applies to all versions of ADO.NET ADO.NET 1.x was built upon industry standards such as XML, and it provided a data-access interface to communicate with data sources such as SQL Server and Oracle ADO.NET 4 continues to build upon these concepts, while increasing performance Applications can use ADO.NET... SQL or Entity Framework Basic ado.neT feaTures This chapter begins with a quick look at the basics of ADO.NET and then provides an overview of ADO NET capabilities, namespaces, and classes It also reviews how to work with the Connection, Command, DataAdapter, DataSet, and DataReader classes Later chapters will cover some of the more recently added ADO.NET features common ado.neT Tasks Before jumping... chapter, you will see that ADO.NET is a very extensive and flexible API for accessing many types of data, and because ADO.NET 4 represents an incremental change to the previous versions of ADO.NET, all previous ADO.NET knowledge already learned can be leveraged In fact, to get the most out of this chapter, you should be fairly familiar with earlier versions of ADO.NET and the entire NET Framework This... the demands made on the resources of a system One of the issues some developers experience when working with ADO.NET and various databases is that you need to leverage at least two languages: Visual Basic and the version of SQL used by the database To reduce this separation, Microsoft developed LINQ, (Language INtegrated Query) With LINQ, you can include the query within your Visual Basic code, and the... beginning of the list instead of the end, which is the default Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Lambda Expressions in Visual Basic ❘  385 Lambda Expressions in Visual Basic While not specifically an XML feature, Visual Basic includes support for lambda expressions These can be quite handy when dealing with XML, or other code that requires some function to be executed... XmlElement, and XmlAttribute The System.Xml namespace also contains classes and interfaces that support stream-style XML access: XmlReader and XmlWriter Next, you looked at how to use XML with ASP.NET While you can use the XmlReader and XmlDocument (and related) classes with ASP.NET, there are included controls to make working with XML easier This chapter also described how to use LINQ to XML and some... to connect to these data sources and retrieve, manipulate, and update data ADO.NET 4 does not break any compatibility with ADO.NET 2.0 or 1.x; it only adds to the stack of functionality In solutions that require disconnected or remote access to data, ADO.NET uses XML to exchange data between programs or with Web pages Any component that can read XML can make use of ADO.NET components A receiving component... to use the ADO.NET object model in order to build flexible, fast, and scalable data-access objects and applications Specifically, it covers the following: ➤➤ The ADO.NET architecture ➤➤ Some of the specific features offered in ADO.NET, including batch updates, DataSet performance improvements, and asynchronous processing ➤➤ Working with the common provider model ➤➤ Using LINQ to query and edit your . how to use it in Visual Basic and the .NET Framework. Among other things, you also need a good understanding of XSLT, XPath, and XQuery. For more details on these standards, see Professional XML. <th>Name</th> XML in ASP .NET ❘ 373 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 3 74 ❘ CHAPTER 9 usiNG xml witH Visual BasiC <th>Painting</th> . XML types to .NET types easier. XML Stream-Style Parsers ❘ 357 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 358 ❘ CHAPTER 9 usiNG xml witH Visual BasiC Using the

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

Từ khóa liên quan

Mục lục

  • WroxBooks

    • Professional Visual Basic 2010 and .NET 4

      • Contents

      • Introduction

      • Part I: Language Constructs and Environment

        • Chapter 1: Visual Studio 2010

          • Visual Studio 2010: Express through Ultimate

          • Visual Basic Keywords and Syntax

          • Project ProVB_VS2010

          • Enhancing a Sample Application

          • Useful Features of Visual Studio 2010

          • Summary

        • Chapter 2: Objects and Visual Basic

          • Object-Oriented Terminology

          • Working With Visual Basic Types

          • Commands: Conditional

          • Value Types (Structures)

          • Reference Types (Classes)

          • Parameter Passing

          • Variable Scope

          • Working with Objects

          • Data Type Conversions

          • Creating Classes

          • Advanced Concepts

          • Summary

        • Chapter 3: Custom Objects

          • Inheritance

          • Multiple Interfaces

          • Abstraction

          • Encapsulation

          • Polymorphism

          • Inheritance

          • Summary

        • Chapter 4: The common language runtime

          • Elements of a .NET Application

          • Versioning and Deployment

          • Cross-Language Integration

          • IL Disassembler

          • Memory Management

          • Namespaces

          • Creating Your Own Namespaces

          • The My Keyword

          • Extending the My Namespace

          • Summary

        • Chapter 5: Declarative Programming with Visual Basic

          • Declarative Programming and Visual Basic

          • Using XAML to Create a Window

          • XAML Syntax

          • Using XAML to Declare a Workflow

          • Summary

        • Chapter 6: Exception Handling and Debugging

          • New in Visual Studio 2010 Team System: Historical Debugging

          • Notes on Compatibility with VB6

          • Exceptions in .NET

          • Structured Exception-Handling Keywords

          • Interoperability with VB6-Style Error Handling

          • Error Logging

          • Summary

        • Chapter 7: Test-Driven Development

          • When and How to Test

          • TDD Tools in Visual Studio

          • UnitTesting Walk-Through

          • Other Visual Studio Editions

          • Third Party Testing Frameworks

          • Summary

      • Part II: Business Objects and Data Access

        • Chapter 8: Arrays, Collections, and Generics

          • Arrays

          • Collections

          • Generics

          • Creating Generics

          • Summary

        • Chapter 9: Using XML with Visual Basic

          • An Introduction to XML

          • XML Serialization

          • System.Xml Document Support

          • XML Stream-Style Parsers

          • XSL Transformations

          • XML in ASP.NET

          • LINQ to XML

          • LINQ Helper XML Objects

          • Visual Basic and XML Literals

          • Using LINQ to Query XML Documents

          • Working with the XML Document

          • Lambda Expressions in Visual Basic

          • Summary

        • Chapter 10: ADO.NET and LINQ

          • ADO.NET Architecture

          • Basic ADO.NET Features

          • .NET Data Providers

          • The DataSet Component

          • Working with the Common Provider Model

          • Connection Pooling in ADO.NET

          • Transactions and System.Transactions

          • LINQ to SQL

          • LINQ to SQL and Visual Basic

          • How Objects Map to LINQ Objects

          • Querying the Database

          • Stored Procedures

          • Updating the Database

          • Summary

        • Chapter 11: Data Access with the Entity Framework

          • Object-Relational Mapping

          • Entity Framework Architecture

          • Mapping Objects to Entities

          • Generating the Database from a Model

          • Summary

        • Chapter 12: Working with SQL Server

          • SQL Server Compact

          • SQL Server’s Built-in XML Features

          • CLR Integration in SQL Server

          • WCF Data Services

          • Summary

        • Chapter 13: Services (XML/WCF)

          • Introduction to Services

          • The Larger Move to SOA

          • Building a WCF Service

          • Building a WCF Consumer

          • Working with Data Contracts

          • Namespaces

          • Summary

      • Part III: Smart Client Applications

        • Chapter 14: Windows Forms

          • The System.Windows.Forms Namespace

          • Using Forms

          • Controls

          • Other Handy Programming Tips

          • Summary

        • Chapter 15: Advanced Windows Forms

          • Packaging Logic in Visual Controls

          • Custom Controls in Windows Forms

          • Inheriting from an Existing Control

          • The Control and UserControl Base Classes

          • A Composite UserControl

          • Building a Control from Scratch

          • Attaching an Icon for the Toolbox

          • Embedding Controls in Other Controls

          • Summary

        • Chapter 16: User Controls Combining WPF and Windows Forms

          • The Integration Library

          • Hosting WPF Controls in Windows Forms

          • Hosting Windows Forms Controls in WPF

          • Integration Limitations

          • Summary

        • Chapter 17: WPF Desktop Applications

          • What, Where, Why, How — WPF Strategy

          • Raster Graphics and Vector Graphics

          • Should Your Next Windows Project Use WPF?

          • Creating a WPF Application

          • Summary

        • Chapter 18: Expression Blend 3

          • Getting to Know Blend

          • SketchFlow

          • Summary

        • Chapter 19: Silverlight

          • What Is Silverlight?

          • Starting a Silverlight Project

          • Silverlight Solution

          • Controls

          • Adding Items to the Silverlight Project

          • Silverlight Out of the Browser

          • Summary

      • Part IV: Internet Applications

        • Chapter 20: Silverlight and Services

          • Services and Silverlight

          • Model-View-ViewModel

          • Summary

        • Chapter 21: Working with ASP.NET

          • The History of ASP.NET

          • Key Features of ASP.NET

          • Visual Studio Support for ASP.NET

          • Building ASP.NET Applications Using Web Forms

          • Data-Driven Applications

          • Summary

        • Chapter 22: ASP.NET Advanced Features

          • Master Pages

          • Navigation

          • Working with the ASP.NET Provider Model

          • Membership and Role Management

          • Profile Properties

          • Microsoft Ajax (ASP.NET AJAX)

          • Summary

        • Chapter 23: ASP.NET MVC

          • Model-View-Controller and ASP.NET

          • Building an ASP.NET MVC Application

          • Summary

        • Chapter 24: SharePoint 2010 Development

          • Introduction

          • Features and the Solutions Framework

          • Visual Studio Tools for SharePoint Development

          • The SharePoint 2010 Object Models

          • Building Web Parts

          • Summary

      • Part V: Libraries and Specialized Topics

        • Chapter 25: Visual Studio Tools for Office

          • Examining the VSTO Releases

          • Office Business Application Architecture

          • Working with Both VBA and VSTO

          • Creating a Document Template (Word)

          • Creating an Office Add-In (Excel)

          • Outlook Form Regions

          • Summary

        • Chapter 26: Windows Workflow Foundation

          • Workflow in Applications

          • Building Workflows

          • Rehosting the Workflow Designer

          • Summary

        • Chapter 27: Localization

          • Cultures and Regions

          • Translating Values and Behaviors

          • ASP.NET Resource Files

          • Resource Files in Windows Forms

          • Summary

        • Chapter 28: COM-Interop

          • Understanding COM

          • COM and .NET in Practice

          • ActiveX Controls

          • Using .NET Components in the COM World

          • P/Invoke

          • Summary

        • Chapter 29: Network Programming

          • Protocols, Addresses, and Ports

          • The System.Net Namespace

          • Sockets

          • Using Internet Explorer in Your Applications

          • Summary

        • Chapter 30: Application Services

          • Using IIS for Application Services

          • Windows Services

          • Characteristics of a Windows Service

          • Interacting with Windows Services

          • Creating a Windows Service

          • Creating a Windows Service in Visual Basic

          • Creating a File Watcher Service

          • Communicating with the Service

          • Custom Commands

          • Passing Strings to a Service

          • Debugging the Service

          • Summary

        • Chapter 31: Assemblies and Reflection

          • Assemblies

          • The Manifest

          • Assemblies and Deployment

          • Versioning Issues

          • Basics of Reflection

          • Dynamic Loading of Assemblies

          • Summary

        • Chapter 32: Security in the .NET Framework

          • Security Concepts and Definitions

          • Permissions in the System.Security.Permissions Namespace

          • Managing Code Access Permission Sets

          • User Access Control

          • Defining Your Application UAC Settings

          • Encryption Basics

          • Summary

        • Chapter 33: Parallel Programming Using Tasks and Threads

          • Launching Parallel Tasks

          • Transforming Sequential Code to Parallel Code

          • Parallelizing Loops

          • Specifying the Desired Degree of Parallelism

          • Creating and Managing Tasks

          • Summary

        • Chapter 34: Deployment

          • Application Deployment

          • Choosing a Framework Version

          • Visual Studio Deployment Projects

          • Modifying the Deployment Project

          • Internet Deployment of Windows Applications

          • IIS Web Deployment Tool

          • Summary

      • Appendices

        • Appendix A: The Visual Basic Compiler

          • The vbc.exe.config File

          • Simple Steps to Compilation

          • Compiler Options

          • Looking at the vbc.rsp File

        • Appendix B: Visual Basic Power Packs Tools

          • Visual Basic Power Packs

          • Using the Interop Forms Toolkit 2.1

          • Using the Power Packs 3.0 Tools

          • Summary

        • Appendix C: Workflow 2008 Specifics

          • Building Workflows

          • Using Workflows with Other Applications

          • Summary

        • Appendix D: Enterprise Services

          • Transactions

          • Transactional Components

          • Other Aspects of Transactions

          • Queued Components

          • Summary

        • Appendix E: Programming for the Cloud

          • The Rise of the Cloud

          • Azure

          • Summary

      • Index

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

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

Tài liệu liên quan