您不需要将文件视为 XML。将文件作为纯文本处理应该没问题。您可以使用String.Substring 方法获取部分字符串。一个简单的分割算法如下所示:
- 定义每个部分的长度 - n
- 从位置 p(最初为 0)开始的字符串中取 n 个字符
- 通过将 p 增加为 n 继续前进
- 循环直到未到达字符串末尾
将字符串分成相等的部分(在这种情况下为 2 部分)的一种可能的解决方案可以这样实现(在这种情况下,要采用的长度将是字符串长度的一半 = 两个相等的部分):
private function chunkify(byval source as string, byval length as integer) as List(of string)
dim chunks = new List(of string)
dim pos = 0
while (pos < source.Length)
dim toTake = length
if not (source.Length - pos) > length then
toTake = source.Length - pos
end if
chunks.Add(source.Substring(pos, toTake))
pos = pos + length
end while
return chunks
end function
在字符串上调用chunkify,使用您希望每个部分具有的长度(您的部分在包含字符串的列表中):
dim content = File.ReadAllText("d:\\xml.xml")
dim chunks = chunkify(content, content.Length / 2)
for each chunk in chunks
Console.WriteLine(chunk)
next chunk
您的内容的输出是:
<?xml version="1.0"?>
<Directory>
<Person>
<Name> John / </Name>
<age> 24 </age>
<DOB>
<year> 1990 </year>
<month> 03 </month>
<date> 23 </date>
</DOB>
' here is the new line from the Console.WriteLine
</Person>
<Person>
<Name> Jane / </Name>
<age> 21 </age>
<DOB>
<year> 1993 </year>
<month> 04 </month>
<date> 25 </date>
</DOB>
</Person>
</Directory>
我建议您将 XML 转换为字节,然后将字节分成相等的部分(在这种情况下,使用 length / 2),因为它可能适合传输。拆分函数的一种可能解决方案如下所示:
function chunkify(byval source as byte(), byval length as integer) as List(Of byte())
' result list containing all parts
dim chunks = new List(of byte())
' the first chunk of content
dim chunk = source.Take(length).ToArray()
do 'loop as long there is something in the array
chunks.Add(chunk)
' remove already read content
source = source.Skip(length).ToArray()
' is there more to take?
chunk = source.Take(length).ToArray()
loop while (chunk.Length > 0)
return chunks
end function
用法如下:
' read all bytes
dim content = File.ReadAllBytes("d:\\xml.xml")
' split into equal parts
dim chunks = chunkify(content, content.Length / 2)
' print / handle each part
for each chunk in chunks
Console.WriteLine(System.Text.Encoding.UTF8.GetString(chunk))
Console.WriteLine("==================================")
next chunk
使用您的示例 XML,拆分后的输出符合预期:
<?xml version="1.0"?>
<Directory>
<Person>
<Name> John / </Name>
<age> 24 </age>
<DOB>
<year> 1990 </year>
<month> 03 </month>
<date> 23 </date>
</DOB>
==================================
</Person>
<Person>
<Name> Jane / </Name>
<age> 21 </age>
<DOB>
<year> 1993 </year>
<month> 04 </month>
<date> 25 </date>
</DOB>
</Person>
</Directory>
==================================