Xml programming bible phần 6 pps

99 260 0
Xml programming bible phần 6 pps

Đ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

456 Part IV ✦ Relational Data and XML The nested elements don’t contain references to the AuthorID or SourceID columns, even though these values are part of the SQL Server tables represented by the nested elements. This information is supplied by the foreign key relationships in the tables and represented by the way that the elements are nested. It’s implied by the element nesting that, for example, the AuthorID and the SourceID for the Quotations data should be supplied by the AuthorID in the Authors parent element. <Quotations QuotationID=”1001” Quotation=”When the hurlyburly’s done, / When the battle’s lost and won.”/> </Sources> </Authors> </XMLProgrammingBIble> Using OPENXML to insert XML data I’ve show you what XML document node trees look like when they are created by OPENXML in an edge table, and I’ve provided an overview of the XML document that I am using for the OPENXML examples. Now I can use OPENXML expressions to insert data into related tables. The code in Listing 18-4 inserts data into three tables from a single XML document. Listing 18-4: Inserting Data into SQL Server Tables Using OPENXML - OPENXMLExample2.sql DECLARE @iDoc int, @cDoc varchar (5000) SET @cDoc = ‘<XMLProgrammingBible> <Authors AuthorID=”1001” AuthorName=”Shakespeare, William”> <Sources SourceID=”1001” Source_Name=”Macbeth”> <Quotations QuotationID=”1001” Quotation=”When the hurlyburlys done, When the battles lost and won.”/> </Sources> </Authors> </XMLProgrammingBible>’ EXEC sp_xml_preparedocument @iDoc OUTPUT, @cDoc INSERT INTO [XMLProgrammingBible].[dbo].[Authors]([AuthorID], [AuthorName]) (SELECT [AuthorID], [AuthorName] FROM OPENXML (@iDoc, ‘/XMLProgrammingBible/Authors’) WITH Authors) INSERT INTO [XMLProgrammingBible].[dbo].[Sources]([SourceID], [Source Name]) (SELECT [SourceID], [Source Name] FROM OPENXML (@iDoc, ‘/XMLProgrammingBible/Authors/Sources’) WITH Sources) INSERT INTO [XMLProgrammingBible].[dbo].[Quotations]([QuotationID], [SourceID], [AuthorID], [Quotation]) i538292 ch18.qxd 8/18/03 8:44 AM Page 456 457 Chapter 18 ✦ Accessing and Formatting XML from SQL Server Data (SELECT QuotationID, SourceID, AuthorID, Quotation FROM OPENXML (@iDoc, ‘/XMLProgrammingBible’) WITH ( QuotationID int ‘./Authors/Sources/Quotations/@QuotationID’, SourceID int ‘./Authors/Sources/@SourceID’, AuthorID int ‘./Authors/@AuthorID’, Quotation char(300) ‘./Authors/Sources/Quotations/@Quotation’)) EXEC sp_xml_removedocument @idoc As with the previous OPENXML example, the first line declares two variables. The iDoc variable is used by the sp_xml_preparedocument stored procedure to parse a provided XML document. The cDoc variable contains the XML document that is parsed. DECLARE @iDoc int, @cDoc varchar (5000) The XML document that is parsed by the sp_xml_preparedocument stored pro- cedure is usually passed via a parameter to the OPENXML command. As with the first example, I’ve explicitly added the document in the code to make it easier to follow the flow. SET @cDoc = ‘<XMLProgrammingBible> <Authors AuthorID=”1001” AuthorName=”Shakespeare, William”> <Sources SourceID=”1001” Source_Name=”Macbeth”> <Quotations QuotationID=”1001” Quotation=”When the hurlyburlys done, When the battles lost and won.”/> </Sources> </Authors> </XMLProgrammingBible>’ sp_xml_preparedocument accepts the integer variable iDoc and the XML docu- ment in the cDoc variable and returns a handle that is used to access the parsed document. EXEC sp_xml_preparedocument @iDoc OUTPUT, @cDoc Next is the first INSERT command. This insert uses a very simple OPENXML SELECT statement to retrieve the AuthorID and AuthorName attributes from the Authors element in the source XML document. The XPath expression locates the element in the XML document. The WITH Authors command at the end of the OPENXML expression tells OPENXML to use the Authors table as a guide when for- matting the node tree. INSERT INTO [XMLProgrammingBible].[dbo].[Authors]([AuthorID], [AuthorName]) (SELECT [AuthorID], [AuthorName] FROM OPENXML (@iDoc, ‘/XMLProgrammingBible/Authors’) WITH Authors) i538292 ch18.qxd 8/18/03 8:44 AM Page 457 458 Part IV ✦ Relational Data and XML The Sources INSERT command is almost identical to the Authors INSERT com- mand. This time, the SourceID and Source_Name attributes from the Sources element in the source XML document are retrieved. The WITH Sources command at the end of the OPENXML expression tells OPENXML to use the Sources table as a guide when formatting the node tree. INSERT INTO [XMLProgrammingBible].[dbo].[Sources]([SourceID], [Source Name]) (SELECT [SourceID], [Source Name] FROM OPENXML (@iDoc, ‘/XMLProgrammingBible/Authors/Sources’) WITH Sources) The Quotations INSERT command has to gather attributes from several elements in the XML document, so unfortunately it can’t use the WITH (table) mapping like Sources and Authors did. Instead, the WITH command contains explicit data typ- ing and mapping. OPENXML explicit mappings gather the Quotation, SourceID, AuthorID, and Quotation attributes from several elements in the XML document. XPath expressions point to positions relative to the root /XMLProgrammingBible element in the XML document. INSERT INTO [XMLProgrammingBible].[dbo].[Quotations]([QuotationID], [SourceID], [AuthorID], [Quotation]) (SELECT QuotationID, SourceID, AuthorID, Quotation FROM OPENXML (@iDoc, ‘/XMLProgrammingBible’) WITH ( QuotationID int ‘./Authors/Sources/Quotations/@QuotationID’, SourceID int ‘./Authors/Sources/@SourceID’, AuthorID int ‘./Authors/@AuthorID’, Quotation char(300) ‘./Authors/Sources/Quotations/@Quotation’)) The last line in the code resets the connection and removes the handle created by sp_xml_preparedocument using the sp_xml_removedocument stored proce- dure with a passed parameter of the XML document handle (iDoc). EXEC sp_xml_removedocument @idoc Using OPENXML to update XML data Updating XML data with OPENXML is very similar to OPENXML data insertion. The code Listing 18-5 updates a row of data in the Sources table with a value provided in an XML document. Listing 18-5: Updating Data in SQL Server Tables Using OPENXML - OPENXMLExample3.sql DECLARE @iDoc int, @cDoc varchar (5000) SET @cDoc = ‘<XMLProgrammingBible> i538292 ch18.qxd 8/18/03 8:44 AM Page 458 459 Chapter 18 ✦ Accessing and Formatting XML from SQL Server Data <Sources SourceID=”1001” Source_Name=”McBeth”> </Sources> </XMLProgrammingBible>’ EXEC sp_xml_preparedocument @iDoc OUTPUT, @cDoc UPDATE Sources SET [Source Name] = XS.Source_Name FROM [XMLProgrammingBible].[dbo].[Sources] S, (SELECT [SourceID], [Source_Name] FROM OPENXML (@iDoc, ‘/XMLProgrammingBible/Authors/Sources’) WITH Sources) XS WHERE S.[Source Name] = ‘Macbeth’ EXEC sp_xml_removedocument @idoc This code starts with the same variable declarations as the previous two examples. The XML document that is passed for the update contains a single row of data to update the Sources table. The SourceID stays the sane, but the Source_Name changes. DECLARE @iDoc int, @cDoc varchar (5000) SET @cDoc = ‘<XMLProgrammingBible> <Sources SourceID=”1001” Source_Name=”McBeth”> </Sources> </XMLProgrammingBible>’ EXEC sp_xml_preparedocument @iDoc OUTPUT, @cDoc The UPDATE command contains a nested SELECT statement that pulls the new value out of the attributes in the XML source document and parses them into nodes. The UPDATE command takes the value of the Source_Name attribute and updates the [Source Name] value in the SQL Server table row. The last line in the code resets the connection and removes the handle created by sp_xml_prepare document using the sp_xml_removedocument stored procedure with a passed parameter of the XML document handle (iDoc). UPDATE Sources SET [Source Name] = XS.Source_Name FROM [XMLProgrammingBible].[dbo].[Sources] S, (SELECT [SourceID], [Source_Name] FROM OPENXML (@iDoc, ‘/XMLProgrammingBible/Authors/Sources’) WITH Sources) XS WHERE S.[Source Name] = ‘Macbeth’ EXEC sp_xml_removedocument @idoc i538292 ch18.qxd 8/18/03 8:44 AM Page 459 460 Part IV ✦ Relational Data and XML Creating an annotated W3C schema for SQL Server data The next part of this chapter will cover XML Bulk Load and Updategram functional- ity, both of which rely heavily on annotated SQL Server schemas. We provided an introduction to five example tables and a simple single-table annotated schema ear- lier in this chapter. Now we’ll produce a single annotated schema that represents the five example SQL Server tables. To create an MS SQL Server Annotated schema, you have a few options. The first option is to hand code a schema using an XML developer tool. This is undesirable for obvious reasons, when using a very large, complex schema. The second option is to use Visual Studio.NET to produce a schema base on the tables. This is the fastest option, but we find that the VS.NET output does not always adhere to the standards of a well-formed W3C schema. In those cases you have to use an editing tool to edit the schema, and hope that it still works with SQL server. The third option is the one that we use the most. Altova’s XMLSpy (a free trial download is available from http://www.xmlspy.com) has a tool that can connect to an SQL Server via OLE and create a W3C schema based on tables that you select. The result is a W3C-compatible schema based on the tables, but without the relationship annotation at the top of the schema. We then manually code the relationship annotation, which took me about five minutes for the four relationship annotations in the example database. The five tables are represented by pieces of a W3C Schema. The relationships between the tables are represented in the annotation at the top of the schema. The rest of the schema is a standard W3C schema format, because we can use the schema defaults to map tables to elements of complex type and attributes of simple type. In other words, because all of the table columns match up to XML document attributes in the schema, the basic, unmapped W3C schema meets our needs. Below is an annotated schema for the five tables in the XMLProgrammingBible database. The first part of the Schema includes an XML document declaration and the W3C and Microsoft namespaces that are used in the schema. The <xs:appinfo> tag in the <xs:annotation> indicates that the annotation has specific information that is reserved for an application that uses the schema. In this case, The relationships between the SQL Server tables are stored in the <xs:appinfo> tag. <?xml version=”1.0” encoding=”UTF-8”?> <xs:schema xmlns:xs=”http://www.w3.org/2001/XMLSchema” xmlns:sql=”urn:schemas- microsoft-com:mapping-schema”> <xs:annotation> <xs:appinfo> The first reference is a foreign key relationship between The Authors table and the AmazonListings table. The primary key is the AuthorID in the Authors table, which is represented by the parent-key and parent attributes in the relationship i538292 ch18.qxd 8/18/03 8:44 AM Page 460 461 Chapter 18 ✦ Accessing and Formatting XML from SQL Server Data element. The foreign key is the AuthorID in the AmazonListings table, which is rep- resented by the child-key and child attributes in the relationship element. Naming the attributes primary-table, primary-key, foreign-table and foreign-key was too easy, we guess <sql:relationship name=”FK_AmazonListings_Authors” parent=”Authors” parent-key=”AuthorID” child=”AmazonListings” child-key=”AuthorID”/> The three remaining relationship elements represent other foreign key relation- ships. The Authors table is also connected to the Quotations table and the ElcorteinglesListings table by a foreign key reference. The Sources table is con- nected to the Quotations table using another foreign key relationship. <sql:relationship name=”FK_ElcorteinglesListings_Authors” parent=”Authors” parent-key=”AuthorID” child=”ElcorteinglesListings” child-key=”AuthorID”/> <sql:relationship name=”FK_Quotations_Authors” parent=”Authors” parent-key=”AuthorID” child=”Quotations” child-key=”AuthorID”/> <sql:relationship name=”FK_Quotations_Sources” parent=”Sources” parent-key=”SourceID” child=”Quotations” child-key=”SourceID”/> </xs:appinfo> </xs:annotation> The first table in the schema is the AmazonListings table. The table is represented by an element containing a W3C schema complex data type. Nested inside the com- plex data type are attributes, some of which contain a W3C schema simple data type. <xs:element name=”AmazonListings”> <xs:complexType> <xs:attribute name=”ProductID” type=”xs:integer”/> <xs:attribute name=”Ranking” type=”xs:integer”/> XMLSPY automatically reproduces field constraints and data types based on SQL server constraints and data types in schemas that are generated from SQL Server databases. For example, the Title column is a W3C schema string data type, and has a maximum length of 200. <xs:attribute name=”Title”> <xs:simpleType> <xs:restriction base=”xs:string”> <xs:maxLength value=”200”/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name=”ASIN”> <xs:simpleType> <xs:restriction base=”xs:string”> i538292 ch18.qxd 8/18/03 8:44 AM Page 461 462 Part IV ✦ Relational Data and XML <xs:maxLength value=”10”/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name=”AuthorID” type=”xs:integer”/> <xs:attribute name=”Image”> <xs:simpleType> <xs:restriction base=”xs:string”> <xs:maxLength value=”100”/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name=”Small_Image”> <xs:simpleType> <xs:restriction base=”xs:string”> <xs:maxLength value=”100”/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name=”List_price” type=”xs:integer”/> <xs:attribute name=”Release_date” type=”xs:dateTime”/> <xs:attribute name=”Binding”> <xs:simpleType> <xs:restriction base=”xs:string”> <xs:maxLength value=”50”/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name=”Availablilty”> <xs:simpleType> <xs:restriction base=”xs:string”> <xs:maxLength value=”10”/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name=”Tagged_URL”> <xs:simpleType> <xs:restriction base=”xs:string”> <xs:maxLength value=”200”/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:complexType> XMLSPY doesn’t create the relationship annotation at the top of the schema, but it does create W3C Schema key and keyref elements representing the relationships via XPath. The keyref element below refers to the foreign key relationship between The AuthorID in the AmazonListings table and the AuthorID in the Authors table. The refer attribute refers to a unique key listed in the Authors table in this schema. The xs:selector and the xs:field elements contain a i538292 ch18.qxd 8/18/03 8:44 AM Page 462 463 Chapter 18 ✦ Accessing and Formatting XML from SQL Server Data reference to XPath expressions for the reference in the current AmazonListings table. The keyref value represents the foreign key, and the key value represents the primary key. <xs:keyref name=”AmazonListings_AuthorID” refer=”Authors_AuthorID”> <xs:selector xpath=”.”/> <xs:field xpath=”@AuthorID”/> </xs:keyref> </xs:element> The Authors table contains the same representational data types and constraints as the AmazonListings table. <xs:element name=”Authors”> <xs:complexType> <xs:attribute name=”AuthorID” type=”xs:integer”/> <xs:attribute name=”AuthorName”> <xs:simpleType> <xs:restriction base=”xs:string”> <xs:maxLength value=”50”/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:complexType> The AuthorID field in the Authors table is the primary key for three relationships in the sample tables. The foreign key relationships are represented by W3C schema keyref elements with a refer attribute back to the Authors_AuthorID key shown here. The field element refers to the authored attribute with an XPath expression (@AuthorID), and the selector element refers to the value in the AuthorID attribute to select with another XPath expression (.). <xs:key name=”Authors_AuthorID”> <xs:selector xpath=”.”/> <xs:field xpath=”@AuthorID”/> </xs:key> </xs:element> The ElcorteinglesListings table repeats the same data typing and constraints shown in the previous tables. <xs:element name=”ElcorteinglesListings”> <xs:complexType> <xs:attribute name=”ProductID” type=”xs:integer”/> <xs:attribute name=”titulo”> <xs:simpleType> <xs:restriction base=”xs:string”> <xs:maxLength value=”200”/> </xs:restriction> i538292 ch18.qxd 8/18/03 8:44 AM Page 463 464 Part IV ✦ Relational Data and XML </xs:simpleType> </xs:attribute> <xs:attribute name=”ISBN”> <xs:simpleType> <xs:restriction base=”xs:string”> <xs:maxLength value=”20”/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name=”AuthorID” type=”xs:integer”/> <xs:attribute name=”Imagen”> <xs:simpleType> <xs:restriction base=”xs:string”> <xs:maxLength value=”100”/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name=”Precio” type=”xs:integer”/> <xs:attribute name=”fecha_de_publicación” type=”xs:dateTime”/> <xs:attribute name=”Encuadernación”> <xs:simpleType> <xs:restriction base=”xs:string”> <xs:maxLength value=”50”/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name=”librourl”> <xs:simpleType> <xs:restriction base=”xs:string”> <xs:maxLength value=”200”/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:complexType> This keyref refers back to the Authors_AuthorID key element in the Authors table. Like the key element in the Authors table, the field element of the keyref element refers to the authored attribute with an XPath expression (@AuthorID), and the selector element refers to the value in the AuthorID selection expres- sion with another XPath expression (.). It also represents a foreign key relationship between the ElcorteinglesListings table and the Authors table. <xs:keyref name=”ElcorteinglesListings_AuthorID” refer=”Authors_AuthorID”> <xs:selector xpath=”.”/> <xs:field xpath=”@AuthorID”/> </xs:keyref> </xs:element> i538292 ch18.qxd 8/18/03 8:44 AM Page 464 [...]... blObject = CreateObject(“SQLXMLBulkLoad.SQLXMLBulkLoad”) blObject.ConnectionString = “provider=SQLOLEDB.1;data source=(local);database=XMLProgrammingBible;Integrated Security=SSPI” blObject.ErrorLogFile = “C:\XMLProgrammingBible\BulkXMLErrors.log” blObject.Execute “C:\XMLProgrammingBible\XMLProgrammingBible.xsd, C:\XMLProgrammingBible\XMLProgrammingBibleWithRelationalData .xml Set blObject=Nothing Main... the one used for the OPENXML insert and update examples The document starts with an XML document declaration, followed by a root element of XMLProgramming Bible The root element can be named anything Because it contains representations of all of the tables in the XMLProgrammingBible database, we named it XMLProgrammingBible < ?xml version=”1.0” encoding=”UTF-8”?> Note that the elements... “C:\XMLProgrammingBible\XMLProgrammingBible.xsd, C:\XMLProgrammingBible\XMLProgrammingBibleWithRelationalData .xml Next, assuming all the inserts went as planned, the object is cleaned up The DTSTaskExecResult_Success constant indicates a successful completion of the XML Bulk Load task Set blObject=Nothing Main = DTSTaskExecResult_Success There are several properties and methods that can be used with XML Bulk... XMLSEQUENCE() function is passed, a single XMLType object is created from the multiple instances in the XMLSequenceType array XMLAGG() SQL /XML Creates an aggregated XML document fragment from a collection of separate XMLType objects SYS_XMLAGG() nests results inside a ROWSET root element, XMLAGG() does not XMLCOLATTVAL() Oracle SQL /XML Extension XMLCOLATTVAL() creates an XML document fragment containing an... XMLTYpeVal SYS.XMLTYPE; BEGIN SELECT XMLELEMENT(“RootElement”, XMLFOREST( PRODUCTID, RANKING, TITLE)) as “result” INTO XMLTYpeVal FROM AmazonListings WHERE rownum = 1; INSERT INTO XMLONLY (XMLDOC) VALUES (XMLTYpeVal); COMMIT; END; 487 488 Part IV ✦ Relational Data and XML Using SQL and SYS_XMLGEN with XMLType columns Now that we have some XMLType data in XMLDOC column of the XMLONLY table, we can extract... combination of XMLAGG(), XMLELEMENT(), XMLATTRIBUTES(), XMLFOREST(), and XMLCOMMATTVAL() are the most common ways to represent relational Oracle data as XML Chapter 19 ✦ Accessing and Formatting XML from Oracle Data Working with the XMLTYPE data type As of Oracle9i the XMLType data type can be used to store an XML data in Oracle databases Before Oracle9i, LOBS and text were used to store XML documents... as XMLType data For more information about XMLType, please refer to the Oracle9i XML Database Developer’s Guide — :Oracle XML DB Chapter 4 Getting data into XMLType columns XMLType columns can be added to any Oracle table (in Oracle9i or above) In this example, we create a table called XMLONLY, which consists of one column, called XMLDOC We assign the data type for XMLDOC as XMLTYPE: CREATE TABLE XMLONLY... XMLONLY (XMLDOC SYS.XMLTYPE); With the new XMLONLY table, we can insert XMLType data from any source In the example below, we select the first three columns of the AMAZONLISTINGS table using nested XMLELEMENT() and XMLFOREST() functions The query selection is inserted into a variable called XMLTypeVal, which is an in-memory XMLType object Next, we insert the XMLType object into the XMLDOC column of the XMLONLY... become attribute values XMLFOREST() SQL /XML Creates XML document fragments from relational data By default, each column name becomes an element name and each column value becomes a text value Nested instances of XMLELEMENT and XMLFOREST() are used to create well-formed XML documents XMLCONCAT() SQL /XML Concatenates multiple XMLType objects into a single XML document If the result of an XMLSEQUENCE() function... XML documents formatted as XMLType data XMLTRANSFORM() Oracle SQL /XML Extension Performs an XSLT transformation on an XML Document using an XSL Stylesheet The XSL stylesheet and the source XML document are passed as XMLType data types The transformation result is returned as another XMLType data object EXTRACT() Oracle SQL /XML Extension Returns an XML document fragment in an XMLType data type format . = “C:XMLProgrammingBibleBulkXMLErrors.log” blObject.Execute “C:XMLProgrammingBibleXMLProgrammingBible.xsd, C:XMLProgrammingBibleXMLProgrammingBibleWithRelationalData .xml Set blObject=Nothing Main. data for each table. blObject.Execute “C:XMLProgrammingBibleXMLProgrammingBible.xsd, C:XMLProgrammingBibleXMLProgrammingBibleWithRelationalData .xml Next, assuming all the inserts went as. representa- tions of all of the tables in the XMLProgrammingBible database, we named it XMLProgrammingBible. < ?xml version=”1.0” encoding=”UTF-8”?> <XMLProgrammingBIble> Note that the elements

Ngày đăng: 09/08/2014, 18:22

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

Tài liệu liên quan