草庐IT

c# - (C#) 如何在不加载或重写整个文件的情况下修改现有 XML 文件中的属性值?

coder 2024-07-01 原文

我在 XmlWriter 和 Linq2Xml 的帮助下制作了一些巨大的 XML 文件(几 GB)。 此文件的类型:

<Table recCount="" recLength="">
<Rec recId="1">..</Rec>
<Rec recId="2">..</Rec>
..
<Rec recId="n">..</Rec>
</Table>

我不知道 Table 的 recCountrecLength 属性的值,直到我写下所有内部 Rec节点,所以我必须在最后为这些属性写入值。

现在我正在将所有内部 Rec 节点写入一个临时文件,计算 Table 的属性值并按照上面显示的方式写入所有内容到结果文件。 (从具有所有 Rec 节点的临时文件中复制所有内容)

我想知道是否有一种方法可以修改这些属性的值而无需将内容写入另一个文件(就像我现在这样做)或将整个文档加载到内存中(这显然是不可能的,因为这些文件的大小)?

最佳答案

大量注释的代码。基本思想是在第一遍中我们写:

<?xml version="1.0" encoding="utf-8"?>
<Table recCount="$1" recLength="$2">
<!--Reserved space:++++++++++++++++-->
<Rec...

然后我们回到文件开头重写前三行:

<?xml version="1.0" encoding="utf-8"?>
<Table recCount="1000" recLength="150">
<!--Reserved space:#############-->

这里重要的“技巧”是你不能“插入”到一个文件中,你只能覆盖它。所以我们为数字“预留”了一些空间(Reserved space:#############. 注释。我们可以通过多种方式完成它...例如,在第一遍中我们可以:

<Table recCount="              " recLength="          ">

然后(xml 合法但丑陋):

<Table recCount="1000          " recLength="150       ">

或者我们可以在 > 之后 添加空格表的:

<Table recCount="" recLength="">                   

(> 之后 有 20 个空格)

然后:

<Table recCount="1000" recLength="150">            

(现在在 > 之后 有 13 个空格)

或者我们可以简单地添加空格而不使用 <!-- -->在一条新线上...

代码:

int maxRecCountLength = 10; // int.MaxValue.ToString().Length
int maxRecLengthLength = 10; // int.MaxValue.ToString().Length
int tokenLength = 4; // 4 == $1 + $2, see below what $1 and $2 are
// Note that the reserved space will be in the form +++++++++++++++++++

string reservedSpace = new string('+', maxRecCountLength + maxRecLengthLength - tokenLength); 

// You have to manually open the FileStream
using (var fs = new FileStream("out.xml", FileMode.Create))

// and add a StreamWriter on top of it
using (var sw = new StreamWriter(fs, Encoding.UTF8, 4096, true))
{
    // Here you write on your StreamWriter however you want.
    // Note that recCount and recLength have a placeholder $1 and $2.
    int recCount = 0;
    int maxRecLength = 0;

    using (var xw = XmlWriter.Create(sw))
    {
        xw.WriteWhitespace("\r\n");
        xw.WriteStartElement("Table");
        xw.WriteAttributeString("recCount", "$1");
        xw.WriteAttributeString("recLength", "$2");

        // You have to add some white space that will be 
        // partially replaced by the recCount and recLength value
        xw.WriteWhitespace("\r\n");
        xw.WriteComment("Reserved space:" + reservedSpace);

        // <--------- BEGIN YOUR CODE
        for (int i = 0; i < 100; i++)
        {
            xw.WriteWhitespace("\r\n");
            xw.WriteStartElement("Rec");

            string str = string.Format("Some number: {0}", i);
            if (str.Length > maxRecLength)
            {
                maxRecLength = str.Length;
            }
            xw.WriteValue(str);

            recCount++;

            xw.WriteEndElement();
        }
        // <--------- END YOUR CODE

        xw.WriteWhitespace("\r\n");
        xw.WriteEndElement();
    }

    sw.Flush();

    // Now we read the first lines to modify them (normally we will
    // read three lines, the xml header, the <Table element and the
    // <-- Reserved space:
    fs.Position = 0;

    var lines = new List<string>();

    using (var sr = new StreamReader(fs, sw.Encoding, false, 4096, true))
    {
        while (true)
        {
            string str = sr.ReadLine();
            lines.Add(str);

            if (str.StartsWith("<Table"))
            {
                // We read the next line, the comment line
                str = sr.ReadLine();
                lines.Add(str);
                break;
            }
        }
    }

    string strCount = XmlConvert.ToString(recCount);
    string strMaxRecLength = XmlConvert.ToString(maxRecLength);

    // We do some replaces for the tokens
    int oldLen = lines[lines.Count - 2].Length;
    lines[lines.Count - 2] = lines[lines.Count - 2].Replace("=\"$1\"", string.Format("=\"{0}\"", strCount));
    lines[lines.Count - 2] = lines[lines.Count - 2].Replace("=\"$2\"", string.Format("=\"{0}\"", strMaxRecLength));
    int newLen = lines[lines.Count - 2].Length;

    // Remove spaces from reserved whitespace
    lines[lines.Count - 1] = lines[lines.Count - 1].Replace(":" + reservedSpace, ":" + new string('#', reservedSpace.Length - newLen + oldLen));

    // We move back to just after the UTF8/UTF16 preamble
    fs.Position = sw.Encoding.GetPreamble().Length;

    // And we rewrite the lines
    foreach (string str in lines)
    {
        sw.Write(str);
        sw.Write("\r\n");
    }
}

较慢的 .NET 3.5 方式

在 .NET 3.5 中 StreamReader/StreamWriter想关基地FileStream ,所以我不得不多次重新打开文件。这有点慢。

int maxRecCountLength = 10; // int.MaxValue.ToString().Length
int maxRecLengthLength = 10; // int.MaxValue.ToString().Length
int tokenLength = 4; // 4 == $1 + $2, see below what $1 and $2 are
                        // Note that the reserved space will be in the form +++++++++++++++++++

string reservedSpace = new string('+', maxRecCountLength + maxRecLengthLength - tokenLength);
string fileName = "out.xml";

int recCount = 0;
int maxRecLength = 0;

using (var sw = new StreamWriter(fileName))
{
    // Here you write on your StreamWriter however you want.
    // Note that recCount and recLength have a placeholder $1 and $2.
    using (var xw = XmlWriter.Create(sw))
    {
        xw.WriteWhitespace("\r\n");
        xw.WriteStartElement("Table");
        xw.WriteAttributeString("recCount", "$1");
        xw.WriteAttributeString("recLength", "$2");

        // You have to add some white space that will be 
        // partially replaced by the recCount and recLength value
        xw.WriteWhitespace("\r\n");
        xw.WriteComment("Reserved space:" + reservedSpace);

        // <--------- BEGIN YOUR CODE
        for (int i = 0; i < 100; i++)
        {
            xw.WriteWhitespace("\r\n");
            xw.WriteStartElement("Rec");

            string str = string.Format("Some number: {0}", i);
            if (str.Length > maxRecLength)
            {
                maxRecLength = str.Length;
            }
            xw.WriteValue(str);

            recCount++;

            xw.WriteEndElement();
        }
        // <--------- END YOUR CODE

        xw.WriteWhitespace("\r\n");
        xw.WriteEndElement();
    }
}

var lines = new List<string>();

using (var sr = new StreamReader(fileName))
{
    // Now we read the first lines to modify them (normally we will
    // read three lines, the xml header, the <Table element and the
    // <-- Reserved space:

    while (true)
    {
        string str = sr.ReadLine();
        lines.Add(str);

        if (str.StartsWith("<Table"))
        {
            // We read the next line, the comment line
            str = sr.ReadLine();
            lines.Add(str);
            break;
        }
    }
}

// We have to use the Stream overload of StreamWriter because
// we want to modify the text!
using (var fs = File.OpenWrite(fileName))
using (var sw = new StreamWriter(fs))
{
    string strCount = XmlConvert.ToString(recCount);
    string strMaxRecLength = XmlConvert.ToString(maxRecLength);

    // We do some replaces for the tokens
    int oldLen = lines[lines.Count - 2].Length;
    lines[lines.Count - 2] = lines[lines.Count - 2].Replace("=\"$1\"", string.Format("=\"{0}\"", strCount));
    lines[lines.Count - 2] = lines[lines.Count - 2].Replace("=\"$2\"", string.Format("=\"{0}\"", strMaxRecLength));
    int newLen = lines[lines.Count - 2].Length;

    // Remove spaces from reserved whitespace
    lines[lines.Count - 1] = lines[lines.Count - 1].Replace(":" + reservedSpace, ":" + new string('#', reservedSpace.Length - newLen + oldLen));

    // We move back to just after the UTF8/UTF16 preamble
    sw.BaseStream.Position = sw.Encoding.GetPreamble().Length;

    // And we rewrite the lines
    foreach (string str in lines)
    {
        sw.Write(str);
        sw.Write("\r\n");
    }
}

关于c# - (C#) 如何在不加载或重写整个文件的情况下修改现有 XML 文件中的属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43186834/

有关c# - (C#) 如何在不加载或重写整个文件的情况下修改现有 XML 文件中的属性值?的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  4. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  5. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  6. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  7. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  8. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  9. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  10. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

随机推荐