XML檔案與實體類的互相轉換

2022-02-13 09:44:25 字數 3234 閱讀 8635

config.xml:

<?

xml version="1.0" encoding="utf-8"

?>

<

config

xmlns:xsi

=""xmlns:xsd

=""isauto

="true"

>

<

description

>定時掃瞄資料庫,通過客戶號和業務號讀取客戶資訊

description

>

<

customerinfos

>

<

customerinfo

>

<

customerid

>0013

customerid

>

<

businessid

>03

businessid

>

customerinfo

>

<

customerinfo

>

<

customerid

>0022

customerid

>

<

businessid

>02

businessid

>

customerinfo

>

customerinfos

>

<

scanconfigs

>

<

begintime

>22:00:00

begintime

>

<

endtimme

>23:00:00

endtimme

>

scanconfigs

>

config

>

2. 為了將上面這個xml轉換為想要的實體類物件,方便在程式裡面讀取節點資料,需要建立乙個相對應的實體類,在實體類中用[xmlroot][xmlelement][xmlattribute]等屬性標識。

config.cs:

//xmlroot表明這個類對應的是xml檔案中的根節點

[xmlroot(elementname="

config")]

public

class

config

//xmlattribute表明這個欄位是xml檔案中當前節點的乙個屬性

[xmlattribute(attributename="is

auto")]

public

string isauto

[xmlelement(elementname = "

customerinfos")]

public

customerinfos customerinfos

[xmlelement(elementname = "

scanconfigs")]

public

scanconfigs scanconfigs

}public

class

customerinfos

}public

class

customerinfo

[xmlelement(elementname = "

businessid")]

public

string businessid

}public

class

scanconfigs

[xmlelement(elementname = "

endtimme")]

public

string endtimme

}

3. 下面的**呼叫.net的xmlserializer類的方法進行xml的反序列化

public

class

xmlutil

}return

result;

}}

4. 反序列化

string xmlpath = "

d:\\config.xml";

config c = xmlutil.deserializefromxml(xmlpath, typeof(config)) as config;

1. 反過來的,也可以將config類的乙個物件序列化為xml檔案.下面的**通過呼叫.net的xmlserializer類的方法將物件序列化為xml檔案

public

class

xmlutil}}

}

2. 序列化

config config = new

config();

config.clientdescribe = "定時掃瞄資料庫,通過客戶號和業務號讀取客戶資訊."

; config.isauto = "true";

customerinfo ci1 = new

customerinfo();

ci1.customerid = "

0013";

ci1.businessid = "03"

; customerinfo ci2 = new

customerinfo();

ci2.customerid = "

0022";

ci2.businessid = "02"

; customerinfos cis = new

customerinfos();

cis.cs = new

customerinfo ;

config.customerinfos =cis;

scanconfigs sc = new

scanconfigs();

sc.begintime = "

22:00:00";

sc.endtimme = "

23:00:00";

config.scanconfigs =sc;

xmlutil.serializetoxml(config, config.gettype(),

"d:\\config.xml

", null);

XML檔案與實體類之間的互相轉換

config.xml xml version 1.0 encoding utf 8 config xmlns xsi xmlns xsd isauto true description 定時掃瞄資料庫,通過客戶號和業務號讀取客戶資訊 description customerinfos custome...

實體類與xml互相轉換通用

實體類序列化成xml 實體.節點名稱 xml轉行為實體類 xml檔案轉化為實體類列表 實體名稱 您的xml檔案 xml標頭檔案 實體列表 public static listxmltoobjlist string xml,string headtag where t new 填充entity類的屬性...

DataTable與實體類互相轉換

datatable與實體類互相轉換 實體類 public class modelhandlerwhere t new else 填充物件列表 用dataset的第index個表填充實體類 public listfillmodel dataset ds,int index else 填充物件列表 用d...