Fastest way to add new node to end of an xml?

前端 未结 10 701
深忆病人
深忆病人 2020-11-29 10:21

I have a large xml file (approx. 10 MB) in following simple structure:


   .......
   .......         


        
10条回答
  •  醉话见心
    2020-11-29 11:08

    Here's how to do it in C, .NET should be similar.

    The game is to simple jump to the end of the file, skip back over the tag, append the new error line, and write a new tag.

    #include 
    #include 
    #include 
    
    int main(int argc, char** argv) {
            FILE *f;
    
            // Open the file
            f = fopen("log.xml", "r+");
    
            // Small buffer to determine length of \n (1 on Unix, 2 on PC)
            // You could always simply hard code this if you don't plan on 
            // porting to Unix.
            char nlbuf[10];
            sprintf(nlbuf, "\n");
    
            // How long is our end tag?
            long offset = strlen("");
    
            // Add in an \n char.
            offset += strlen(nlbuf);
    
            // Seek to the END OF FILE, and then GO BACK the end tag and newline
            // so we use a NEGATIVE offset.
            fseek(f, offset * -1, SEEK_END);
    
            // Print out your new error line
            fprintf(f, "New error line\n");
    
            // Print out new ending tag.
            fprintf(f, "\n");
    
            // Close and you're done
            fclose(f);
    }
    

提交回复
热议问题