Tải bản đầy đủ - 0 (trang)
Chapter 9. Working with XML Data

Chapter 9. Working with XML Data

Tải bản đầy đủ - 0trang

Containsclassesthatprovidestandards-basedsupportfor

processingXML.



System.Xml.Linq

ContainsclassesthatprovidesupportforLINQtoXML.



System.Xml.Schema

Containsclassesthatprovidestandards-basedsupportfor

XMLSchemaDefinition(XSD)languageschemas.



System.Xml.Serialization

ContainsclassesthatserializeobjectsintoXMLdocuments

orstreams.



System.Xml.XPath

ContainsclassesthatparseandevaluateXPath.



System.Xml.Xsl

ContainsclassesthatsupportExtensibleStylesheet

Language(XSL)transformations.

.NETFrameworkclassessupportsavingandloadingbothXML

dataandschemafromandtoADO.NETdisconnectedclasses.

Section9.1showshowtoloadXMLdataintoaDataSetor

DataTableandhowtosavedatainaDataSetorDataTableto

anXMLfile.Section9.2showshowtoloadanXMLschemainto

aDataSetandhowtosavetheschemaofaDataSetasanXML

schemafile.Section9.3showshowtocustomizetheformatof



XMLdatasavedfromaDataSet.

TheDiffGramisanXMLformatthatidentifiescurrentand

originalversionsofdataallowingthecontentsofaDataSetto

berecreatedaccurately.TheDiffGramallowsyoutoidentifythe

changesmadetoaDataSetsinceitwasfilled.TheDataSet

usestheDiffGramformattopersistandtoserializeitscontents

fortransportacrossanetwork.Section9.4showshowtocreate

aDiffGramofchangesmadetoaDataSet.

The.NETFrameworkallowsreal-time,synchronousaccessto

bothaDataSetanditsXMLrepresentationinan

XmlDataDocumentobject.ThesynchronizedDataSetand

XmlDataDocumentclassesworkwithasinglesetofdata—

changestoonearereflectedimmediatelyintheother.Section

9.5showshowtosimultaneouslyworkwithADO.NETandXML

representationsofthesamesynchronizeddata.

Section9.6showsyouhowtosaveandretrieveXMLina

databasecolumnthatisnotxmldatatyped.Section9.7shows

howtosaveandretrievedatastoredinanxmldatatype

columnintroducedinSQLServer2005.

ADO.NETsupportsXPathqueriesagainstaDataSet.Section9.8

showsyouhow.

SQLServersupportsretrievingtheresultsofqueriesinXML

formatusingtheFORXMLclause.TheXmlReaderprovides

directforward-only,read-onlyaccesstotheXMLresultset

streamfromtheSQLServer.Section9.9showshowtousethe

FORXMLclausetoretrieveXML-formatdatafromaSQLServer

usinganXmlReader.

TheSQLXMLmanagedclassesexposeSQLXMLfunctionalitythat

allows.NETapplicationstoaccessXMLdatafromSQLServer,

processtheXMLdata,andupdatetheSQLServerusinganXML

DiffGramrepresentationofthedata.SQLXMLclassessupport



templatequeries,anXMLdocumentcontainingoneormore

SQLqueriesorstoredprocedures,toexecute.Section9.11

showshowtousetemplatequeries.

OPENXMLallowsanXMLdocumenttobeusedinaSQL

statementinthesamewayatableorviewisused.Section9.12

showshowtouseOPENXMLfromADO.NET.



Chapter9.WorkingwithXMLData

Introduction

UsinganXMLFiletoSaveandLoadaDataSetoraDataTable

UsingXSDSchemaFilestoSaveandLoadaDataSetStructure

FormattingColumnValuesWhenSavingDataAsXML

CreatinganXMLFileThatShowsChangesMadetoaDataSet

SynchronizingaDataSetandanXMLDocument

StoringandRetrievingXMLwithaNon-XMLDataTypeColumn

WorkingwithaSQLServerXMLDataTypeColumn

UsinganXPathQuerytoRetrieveData

ReadingXMLDataDirectlyfromSQLServer

TransformingaDataSetUsingXSLT

FillingaDataSetUsinganXMLTemplateQuery

UsingOpenXMLtoUpdateMultipleChangestoSQLServer



Recipe9.0.Introduction

ADO.NETandXMLclassesaretightlyintegratedinthe.NET

Framework.TheDataSetcanbefilledwithdataoraschema

fromanXMLstreamordocument.TheDataSetcanpersistor

serializeitsdataorschematoanXMLstreamordocument.You

cansimultaneouslyworkwiththesamedatainaDataSetand

withitsXMLrepresentation.ThischapterfocusesonXML

supportinADO.NETandinSQLServer.

TheXMLsupportin.NETisprovidedbyclassesinsix

namespaces:

System.Xml



Containsclassesthatprovidestandards-basedsupportfor

processingXML.



System.Xml.Linq

ContainsclassesthatprovidesupportforLINQtoXML.



System.Xml.Schema

Containsclassesthatprovidestandards-basedsupportfor

XMLSchemaDefinition(XSD)languageschemas.



System.Xml.Serialization

ContainsclassesthatserializeobjectsintoXMLdocuments

orstreams.



System.Xml.XPath

ContainsclassesthatparseandevaluateXPath.



System.Xml.Xsl

ContainsclassesthatsupportExtensibleStylesheet

Language(XSL)transformations.

.NETFrameworkclassessupportsavingandloadingbothXML

dataandschemafromandtoADO.NETdisconnectedclasses.

Section9.1showshowtoloadXMLdataintoaDataSetor

DataTableandhowtosavedatainaDataSetorDataTableto

anXMLfile.Section9.2showshowtoloadanXMLschemainto

aDataSetandhowtosavetheschemaofaDataSetasanXML

schemafile.Section9.3showshowtocustomizetheformatof



XMLdatasavedfromaDataSet.

TheDiffGramisanXMLformatthatidentifiescurrentand

originalversionsofdataallowingthecontentsofaDataSetto

berecreatedaccurately.TheDiffGramallowsyoutoidentifythe

changesmadetoaDataSetsinceitwasfilled.TheDataSet

usestheDiffGramformattopersistandtoserializeitscontents

fortransportacrossanetwork.Section9.4showshowtocreate

aDiffGramofchangesmadetoaDataSet.

The.NETFrameworkallowsreal-time,synchronousaccessto

bothaDataSetanditsXMLrepresentationinan

XmlDataDocumentobject.ThesynchronizedDataSetand

XmlDataDocumentclassesworkwithasinglesetofdata—

changestoonearereflectedimmediatelyintheother.Section

9.5showshowtosimultaneouslyworkwithADO.NETandXML

representationsofthesamesynchronizeddata.

Section9.6showsyouhowtosaveandretrieveXMLina

databasecolumnthatisnotxmldatatyped.Section9.7shows

howtosaveandretrievedatastoredinanxmldatatype

columnintroducedinSQLServer2005.

ADO.NETsupportsXPathqueriesagainstaDataSet.Section9.8

showsyouhow.

SQLServersupportsretrievingtheresultsofqueriesinXML

formatusingtheFORXMLclause.TheXmlReaderprovides

directforward-only,read-onlyaccesstotheXMLresultset

streamfromtheSQLServer.Section9.9showshowtousethe

FORXMLclausetoretrieveXML-formatdatafromaSQLServer

usinganXmlReader.

TheSQLXMLmanagedclassesexposeSQLXMLfunctionalitythat

allows.NETapplicationstoaccessXMLdatafromSQLServer,

processtheXMLdata,andupdatetheSQLServerusinganXML

DiffGramrepresentationofthedata.SQLXMLclassessupport



templatequeries,anXMLdocumentcontainingoneormore

SQLqueriesorstoredprocedures,toexecute.Section9.11

showshowtousetemplatequeries.

OPENXMLallowsanXMLdocumenttobeusedinaSQL

statementinthesamewayatableorviewisused.Section9.12

showshowtouseOPENXMLfromADO.NET.



Recipe9.1.UsinganXMLFiletoSave

andLoadaDataSetoraDataTable

9.2.1.Problem

YouneedtosaveaDataSetorDataTableasanXMLfileand

createaDataSetorDataTablefromanXMLfile.



9.2.2.Solution

UsetheXmlTextWriterandXmlTextReaderclassestogether

withtheWriteXml()andReadXml()methodsoftheDataSet

andDataTableclasses.

ThesolutioncreatesaDataSetcontainingasubsetofdatafrom

thePerson.ContacttableinAdventureWorks.TheXMLschema

anddatafortheDataSetiswrittentoafilenamed

ContactDataset.xml.Next,thesolutioncreatesaDataSetand

readsinschemaanddatafromtheXMLfile

ContactDataSet.xml.Finally,thecontentsoftheDataSetare

writtentotheconsole.

TheC#codeinProgram.csintheprojectSaveLoadDataSetXml

isshowninExample9-1.

Example9-1.File:Program.csforSaveLoadDataSetXml

solution

CodeView:

usingSystem;

usingSystem.Data;

usingSystem.Data.SqlClient;

usingSystem.IO;

usingSystem.Xml;

usingSystem.Text;

namespaceSaveLoadDataSetXml



{

classProgram

{

privateconststringfileName=@"..\..\..\ContactDataS



staticvoidMain(string[]args)

{

stringsqlConnectString="DataSource=(local);"+

"Integratedsecurity=SSPI;InitialCatalog=Adven



stringsqlSelect="SELECTContactID,FirstName,La

"FROMPerson.ContactWHEREContactIDBETWEEN10



//FilltheDataSetusingaDataAdapter

DataSetdsSource=newDataSet("ContactDataSet");

SqlDataAdapterda=newSqlDataAdapter(sqlSelect,s

da.TableMappings.Add("Table","Contact");

da.FillSchema(dsSource,SchemaType.Source);

da.Fill(dsSource);



//OutputtheDataSettotheconsole

Console.WriteLine("---SourceDataSet---");

foreach(DataRowrowindsSource.Tables["Contact"].

Console.WriteLine("ContactID={0}\tFirstName=

row["ContactID"],row["FirstName"],row["La



//WritetheXSDschemaanddatatoafile.

FileStreamfsOut=

newFileStream(fileName,FileMode.Create,FileA

//CreateanXmlTextWriterusingthefilestream.

XmlTextWriterxtw=newXmlTextWriter(fsOut,Encodi

//WritetheXMLtothefile.

dsSource.WriteXml(xtw,XmlWriteMode.WriteSchema);

xtw.Close();

Console.WriteLine("\nXMLfilewritten.");

//ReadtheXMLfileintoanewDataSet

FileStreamfsIn=



newFileStream(fileName,FileMode.Open,FileAcc

//CreateanXmlTextReaderusingthefilestream.

XmlTextReaderxtr=newXmlTextReader(fsIn);

DataSetdsDest=newDataSet();

dsDest.ReadXml(xtr,XmlReadMode.ReadSchema);



//OutputtheDataSettotheconsole.

Console.WriteLine("\nXMLfileloadedintoDataSet."

Console.WriteLine("\n---DestinationDataSet---");

foreach(DataRowrowindsDest.Tables["Contact"].Ro

Console.WriteLine("ContactID={0}\tFirstName=

row["ContactID"],row["FirstName"],row["La

Console.WriteLine("\nPressanykeytocontinue.");

Console.ReadKey();

}

}

}

























TheoutputisshowninFigure9-1.

Figure9-1.OutputforSaveLoadDataSetXmlsolution



9.2.3.Discussion

ThesolutionusestheXmlTextWriterandXmlTextReader



classestowriteandreadtheXMLdatafortheDataSet.The

XmlTextWriterclassprovidesaforward-onlymechanismfor

generatingXMLstreamsorfilescontainingXMLdata.The

XmlTextReaderclassprovidesforward-onlyaccesstoXMLdata

instreamsorfiles.TheXmlTextReaderdoesnotvalidatethe

XML—forvalidation,usetheXmlValidatingReaderclass.Both

theXmlTextWriterandXmlTextReaderclassesconformtothe

W3CXML1.0andthenamespacesinXMLrecommendations.

TheXMLfileencodingusedbytheXmlTextWriterisspecified

inanargumenttotheconstructorasoneofthevaluesfromthe

System.Text.EncodingenumerationdescribedinTable9-1.

Table9-1.System.Text.Encodingenumeration

Encoding



Description



ASCII



ASCII(7bit)characterset



BigEndianUnicode Unicodeformatinbig-endianbyteorder

Default



Encodingforsystem'scurrentANSIcode

page



Unicode



Unicodeformatinlittle-endianbyteorder



UTF7



UTF-7format



UTF8



UTF-8format(thisisthedefault)



TheWriteXml()andReadXml()methodsoftheDataSetand

DataTableclassesareusedtowriteandreadXMLforobjectsof

thosetypes.TheWriteXml()methodtakesanoptional

argumentthatspecifiesavaluefromtheXmlWriteMode

enumerationdescribedinTable9-2.

Table9-2.XmlWriteModeenumeration

Value



Description



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 9. Working with XML Data

Tải bản đầy đủ ngay(0 tr)

×