读取一个大的1 GB xml文件

时间:2014-04-28 06:38:25

标签: c# readxml

我需要打开一个大型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>

1 个答案:

答案 0 :(得分:1)

像这样的东西

        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();
        }