Convert data objects in asp.net to XML data format

Source: Internet
Author: User
Tags xml attribute

This article introduces how to convert data objects in the xml format in asp.net, including, read and generate xml and tabledata conversion xml documents directly from the database. For more information, see.

This involves converting an Object into an XML data format. I found some information online. Here we will summarize the methods currently used.

The main conversion code is as follows:

The Code is as follows: Copy code

Public static Stream TransforToXMLFormat (object obj)
{
XmlSerializerFactory xmlSerializerFactory = new XmlSerializerFactory ();


XmlSerializer xmlSerializer = new XmlSerializer (obj. GetType ());


MemoryStream stream = new MemoryStream ();


XmlSerializer. Serialize (stream, obj );


Return stream;
}

The. Net reflection mechanism is very simple. The generated XML is acceptable. Important Notes:

1. The class must have the Name attribute. Otherwise, an error will be reported during conversion!

2. Use [XmlAttribute] to place it on the Name, that is:

The Code is as follows: Copy code

[XmlAttribute]
Public string Name;

You can change Name to an XML Attribute instead of an XML element, that is:

The Code is as follows: Copy code

<Class xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "http://www.w3.org/2001/XMLSchema" Name = "......">

Instead:

The Code is as follows: Copy code

<Class xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "http://www.w3.org/2001/XMLSchema">

<Name> </Name>

</Class>

 

3. to output an attribute as an XML element, the attribute must be public.

4. the output uses List <>. To change the class name of each element in the List, add [XmlElement (ElementName = "name to be changed") to List <>. That is:

The Code is as follows: Copy code

[XmlElement (ElementName = "name to be changed")]
Public List <Type> Objects = null;

Append the operation to convert the value in Hashtable into a List.

The Code is as follows: Copy code

List <Object> = HashtableObject. Values. Cast <Object> (). ToList ();


DataTable into XML file

Database Table position has three fields:
Field Name field type
Position_id int
Position_name varchar
Position_desc varchar
The source code for Datatable to XML Conversion is as follows:

The Code is as follows: Copy code
Protected void Page_Load (object sender, EventArgs e)
{
// Read the position to the able through the data access layer
BizRules. PersonnelDAL pl = new PersonnelDAL ();
DataTable dt = pl. Getposition ();
StringBuilder str = new StringBuilder ();
Str. Append (DataTableToXml (dt ));
This. CreateXml (str. ToString (), "test. xml ");
Response. Write ("test. xml generated successfully ");
}
/// <Summary>
/// Generate a file
/// </Summary>
/// <Param name = "val"> </param>
/// <Param name = "filename"> </param>
Public void CreateXml (string val, string filename)
{
UnicodeEncoding ucode = new UnicodeEncoding ();
StreamWriter sw = new StreamWriter (Server. MapPath (filename ));
Sw. WriteLine ("<? Xml version = "1.0" encoding = "UTF-8"?> ");
Sw. WriteLine (val );
Sw. Close ();
Sw. Dispose ();
}
/// <Summary>
/// Convert to an XML string
/// </Summary>
/// <Param name = "dt"> </param>
/// <Returns> </returns>
Public string DataTableToXml (DataTable dt)
{
StringBuilder strXml = new StringBuilder ();
StrXml. AppendLine ("<XmlTable> ");
For (int I = 0; I <dt. Rows. Count; I)
{
StrXml. AppendLine ("<rows> ");
For (int j = 0; j <dt. Columns. Count; j)
{
StrXml. appendLine ("<" dt. columns [j]. columnName ">" dt. rows [I] [j] "</" dt. columns [j]. columnName "> ");
}
StrXml. AppendLine ("</rows> ");
}
StrXml. AppendLine ("</XmlTable> ");
Return strXml. ToString ();
}

The following describes how to generate an XML file:

The Code is as follows: Copy code
<? Xml version = "1.0" encoding = "UTF-8"?>
<XmlTable>
<Rows>
<Position_id> 29 </position_id>
<Position_name> salesman </position_name>
<Position_desc> </position_desc>
</Rows>
<Rows>
<Position_id> 30 </position_id>
<Position_name> business manager </position_name>
<Position_desc> </position_desc>
</Rows>
<Rows>
<Position_id> 31 </position_id>
<Position_name> Business Director </position_name>
<Position_desc> </position_desc>
</Rows>
</XmlTable>

If you use DataSet, you can convert the DataSet into a able, and then use the above method.


Data conversion xml file

Save data from database query results to XML files

The Code is as follows: Copy code

<% @ Import Namespace = "System. Data" %>
<% @ Import Namespace = "System. Data. OleDb" %>

<Script language = "VB" runat = "server">

Sub Page_Load (Sender As Object, E As EventArgs)

Dim strConnection As String
Dim strSQL As String
Dim objDataSet As New DataSet ()
Dim objConnection As OleDbConnection
Dim objAdapter As OleDbDataAdapter

StrConnection = "Provider = Microsoft. Jet. OLEDB.4.0 ;"&_
"Data Source =" + MapPath ("EmployeeDatabase. mdb ")
StrSQL = "SELECT FirstName, LastName FROM Employee ;"

ObjConnection = New OledbConnection (strConnection)
ObjAdapter = New OledbDataAdapter (strSQL, objConnection)

ObjAdapter. Fill (objDataSet, "Employees ")

ObjDataSet. WriteXml (Server. MapPath ("Employee2.xml "))

Response. Write ("XML File Generated ")

End Sub

</Script>

For more details, see http://www.bKjia. c0m/net/37/38865 .htm

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.