將具有特殊格式的文件轉化為xml文件
2024-09-05 20:55:51
供稿:網友
假如我們現在有這樣的一個文件food.tab
內容如下:
room_number breakfast lunch dinner
290 bagel pizza salmon
301 orange pizza chicken ala king
349 sweet roll salad tofu and vegetables
500 omelet sausage veal
702 eggs tuna fish cheese sandwich
文件中每一項都是用vbtab進行分割的
那么現在我們要把它自動轉化為一個如下的xml文件
<kitchen xmlns="the_roach_motel">
<room_service>
<room_number>290</room_number>
<breakfast>bagel</breakfast>
<lunch>pizza</lunch>
<dinner>salmon</dinner>
</room_service>
<room_service>
<room_number>301</room_number>
<breakfast>orange</breakfast>
<lunch>pizza</lunch>
<dinner>chicken ala king</dinner>
</room_service>
<room_service>
<room_number>349</room_number>
<breakfast>sweet roll</breakfast>
<lunch>salad</lunch>
<dinner>tofu and vegetables</dinner>
</room_service>
<room_service>
<room_number>500</room_number>
<breakfast>omelet</breakfast>
<lunch>sausage</lunch>
<dinner>veal</dinner>
</room_service>
<room_service>
<room_number>702</room_number>
<breakfast>eggs</breakfast>
<lunch>tuna fish</lunch>
<dinner>cheese sandwich</dinner>
</room_service>
</kitchen>
我們需要怎么做呢:
我們需要利用streamreader來讀取文件內容,存放到一個臨時的dataset中,最后用dataset的getxml()來得到這個xml文件
let'go
code:
imports system
imports system.io
imports system.collections
imports system.data
imports system.text
module modxml
sub main()
dim strxml as string
strxml = delimiteddataset(vbtab, "c:/food.tab")
'你可能需要進行必要的修改
end sub
function delimiteddataset(byval strdelimiter as string, _
byval strfilepath as string) as string
dim ods as new dataset()
dim strfields as string
dim otable as new datatable()
dim orows as datarow
dim intcounter as int32 = 0
dim orow as datarow()
ods.datasetname = "kitchen"
ods.namespace = "the_roach_motel"
ods.tables.add("room_service")
dim osr as new streamreader(strfilepath)
'到文件的頭
osr.basestream.seek(0, seekorigin.begin)
'添加到 header columns
for each strfields in osr.readline().split(strdelimiter)
ods.tables(0).columns.add(strfields)
next
'現在添加rows
otable = ods.tables(0)
while (osr.peek() > -1)
orows = otable.newrow()
for each strfields in osr.readline().split(strdelimiter)
orows(intcounter) = strfields
intcounter = intcounter + 1
next
intcounter = 0
otable.rows.add(orows)
end while
return ods.getxml()
'ods.writexml("c:/food.xml")
'或者將它寫到硬盤上
end function
,歡迎訪問網頁設計愛好者web開發。