正在读取1 GB的大xml文件
本文关键字:的大 xml 文件 GB 读取 | 更新日期: 2023-09-27 18:00:32
我需要打开一个大的XML文件,并将一个AddressInfo
元素附加到现有文件中。做这件事最好、最快的方法是什么?
我的XML示例:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfAddressInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<AddressInfo>
<Level1></Level1>
<Level2>2010-10-29T19:53:32</Level2>
<Level3>/Level3>
<Level4></Level4>
</AddressInfo>
<AddressInfo>
<Level1></Level1>
<Level2>2010-10-29T19:53:32</Level2>
<Level3>/Level3>
<Level4></Level4>
</AddressInfo>
</ArrayOfAddressInfo>
类似的东西
string lastTag = "</ArrayOfAddressInfo>";
string newNode = "'r'n<AddressInfo>'r'n<Level1/>'r'n</AddressInfo>";
int offset = 5;
using (FileStream xmlstream = new FileStream(
@"test.xml",
FileMode.Open,
FileAccess.ReadWrite,
FileShare.None))
{
// Get to the appx position, assumes the last tag is the
// last thing in the file. Adjust the offset accordingly
// for your needs
xmlstream.Seek(-(lastTag.Length + offset), SeekOrigin.End);
// Check - are we at the >
while (xmlstream.ReadByte() != '>')
;
// Write our bit of xml
xmlstream.Write(
Encoding.ASCII.GetBytes(newNode),
0, newNode.Length);
// Rewrite the last tag
xmlstream.Write(
Encoding.ASCII.GetBytes("'r'n" + lastTag + "'r'n"),
0, lastTag.Length + 2);
xmlstream.Close();
}