I have an XML template with all the headers I need. I load it with XDocument
, and then build the nodes using XElements
. However, this means I am currently hard coding the data bits I need to go into my file.
I noticed with SQL Server I can use the XML
datatype to store data in the database. Using this approach it would be better to look through each record and dynamically build the XML
file.
However, I see some issues with my approach. There may be two nodes that share the same parent. Is there a way to store the nodes and their parent, and use something in XDocument
to merge them?
Here is a sample chunk of my XML
<AddInfoCollection>
<AddInfo>
<Key>TransportReference</Key>
<Value>666777888</Value>
</AddInfo>
<AddInfo>
<Key>UI_NKCarrierSCAC</Key>
<Value>ABCD</Value>
</AddInfo>
<AddInfo>
<Key>SchDLoading</Key>
<Value>1234</Value>
</AddInfo>
<AddInfo>
<Key>SchDArrival</Key>
<Value>12345</Value>
</AddInfo>
</AddInfoCollection>
In the database, I'd imagine the table would be:
Field (varchar(200)
Value (varchar(200)
XML
Sample:
Field Value XML
----------------------------------------------------------------
TransportReference 666777888 <AddInfoCollection>
<AddInfo>
<Key>TransportReference</Key>
<Value>666777888</Value>
</AddInfo>
<AddInfoCollection>
Use SELECT... FOR XML .
For example:
USE ADVENTUREWORKS
SELECT TOP 2 * FROM HUMANRESOURCES.EMPLOYEE FOR XML PATH
This returns the resultset as the following XML. Use other variants of SELECT...FOR XML to tailor the XML to your requirements.
<row>
<EmployeeID>1</EmployeeID>
<NationalIDNumber>14417807</NationalIDNumber>
<ContactID>1209</ContactID>
<LoginID>adventure-works\guy1</LoginID>
<ManagerID>16</ManagerID>
<Title>Production Technician - WC60</Title>
<BirthDate>1972-05-15T00:00:00</BirthDate>
<MaritalStatus>M</MaritalStatus>
<Gender>M</Gender>
<HireDate>1996-07-31T00:00:00</HireDate>
<SalariedFlag>0</SalariedFlag>
<VacationHours>21</VacationHours>
<SickLeaveHours>30</SickLeaveHours>
<CurrentFlag>1</CurrentFlag>
<rowguid>AAE1D04A-C237-4974-B4D5-935247737718</rowguid>
<ModifiedDate>2004-07-31T00:00:00</ModifiedDate>
</row>
<row>
<EmployeeID>2</EmployeeID>
<NationalIDNumber>253022876</NationalIDNumber>
<ContactID>1030</ContactID>
<LoginID>adventure-works\kevin0</LoginID>
<ManagerID>6</ManagerID>
<Title>Marketing Assistant</Title>
<BirthDate>1977-06-03T00:00:00</BirthDate>
<MaritalStatus>S</MaritalStatus>
<Gender>M</Gender>
<HireDate>1997-02-26T00:00:00</HireDate>
<SalariedFlag>0</SalariedFlag>
<VacationHours>42</VacationHours>
<SickLeaveHours>41</SickLeaveHours>
<CurrentFlag>1</CurrentFlag>
<rowguid>1B480240-95C0-410F-A717-EB29943C8886</rowguid>
<ModifiedDate>2004-07-31T00:00:00</ModifiedDate>
</row>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.