将具有特殊格式的文件转化为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开发。