You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#实现类XML片段文件的内容编辑需求求助

含XML片段的文件编辑优化实现方案

需求说明

处理仅内部片段为XML格式的文件,需完成以下操作:

  • 在文件中查找包含Module Name="+0.1.2HUB" Type="0AC808.9"的行
  • 找到该行后,在对应位置插入指定的Connection XML片段
  • 未找到时,写入完整的Module节点内容

现有实现代码

当前仅实现了目标Module的存在判断:

using (StreamReader sr = new StreamReader(pathFile))
{
    string line;
    // Read and display lines from the file until the end of
    // the file is reached.
    while ((line = sr.ReadLine()) != null)
    {
        string compare = "<Module Name=\"" + moduleName + "\" Type=\"0AC808.9\"";
 
        // look for an string 
        if (line.Contains(compare))
        {
            return true; // 原代码大写True不符合C#语法,已修正
        }
    }
    return false; // module not found
}

待插入/新增内容

需插入的Connection片段

<Connection Connector="ETH2" TargetModule="+0.1.2HUB" TargetConnector="PLK1">
    <Cable Type="PowerlinkCable" Length="10" Version="1.0.0.3" />
 </Connection>

(注:原片段存在XML语法错误,已修正自闭合标签为正常嵌套标签)

未找到时需写入的完整Module节点

<Module Name="+0.1.2HUB" Type="0AC808.9" Frozen="true" LastFrozenVersion="1.0.0.0" Version="1.0.0.0">
 <Connection Connector="ETH1" TargetModule="+0.1.2HUB" TargetConnector="PLK1">
    <Cable Type="PowerlinkCable" Length="10" Version="1.0.0.3" />
 </Connection>
 <Connection Connector="ETH8" TargetModule="80274418TLS03" TargetConnector="IF3">
    <Cable Type="PowerlinkCable" Length="10" Version="1.0.0.3" />
 </Connection>
</Module>

优化实现方案

由于文件仅部分为XML格式,无法直接使用XML解析库处理,因此采用逐行读写+临时文件替换的方案,兼顾性能和准确性:

核心思路

  1. 使用StreamReader逐行读取原文件,同时用StreamWriter写入临时文件
  2. 匹配到目标Module行时,先写入该行,再插入指定的Connection片段(保持缩进一致)
  3. 若全程未匹配到目标Module,在文件末尾写入完整的Module节点
  4. 操作完成后用临时文件替换原文件

完整代码实现

using System.IO;

public void UpdateModuleFile(string pathFile, string moduleName)
{
    string tempFilePath = Path.GetTempFileName();
    bool moduleFound = false;
    string targetModuleLinePattern = $"<Module Name=\"{moduleName}\" Type=\"0AC808.9\"";
    string connectionToInsert = @"
 <Connection Connector=""ETH2"" TargetModule=""+0.1.2HUB"" TargetConnector=""PLK1"">
    <Cable Type=""PowerlinkCable"" Length=""10"" Version=""1.0.0.3"" />
 </Connection>";
    string fullModuleToAdd = @"
<Module Name=""+0.1.2HUB"" Type=""0AC808.9"" Frozen=""true"" LastFrozenVersion=""1.0.0.0"" Version=""1.0.0.0"">
 <Connection Connector=""ETH1"" TargetModule=""+0.1.2HUB"" TargetConnector=""PLK1"">
    <Cable Type=""PowerlinkCable"" Length=""10"" Version=""1.0.0.3"" />
 </Connection>
 <Connection Connector=""ETH8"" TargetModule=""80274418TLS03"" TargetConnector=""IF3"">
    <Cable Type=""PowerlinkCable"" Length=""10"" Version=""1.0.0.3"" />
 </Connection>
</Module>";

    try
    {
        using (StreamReader reader = new StreamReader(pathFile))
        using (StreamWriter writer = new StreamWriter(tempFilePath))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                writer.WriteLine(line);

                // 检查当前行是否为目标Module行
                if (line.Contains(targetModuleLinePattern))
                {
                    moduleFound = true;
                    // 插入Connection片段,保持缩进与原文件一致
                    writer.WriteLine(connectionToInsert.TrimStart());
                }
            }

            // 若未找到目标Module,在文件末尾添加完整节点
            if (!moduleFound)
            {
                writer.WriteLine(fullModuleToAdd.TrimStart());
            }
        }

        // 替换原文件
        File.Delete(pathFile);
        File.Move(tempFilePath, pathFile);
    }
    finally
    {
        // 清理临时文件(如果替换失败)
        if (File.Exists(tempFilePath))
        {
            File.Delete(tempFilePath);
        }
    }
}

关键优化点

  • 使用字符串插值简化匹配模式拼接,避免转义错误
  • 采用临时文件写入,避免原文件被破坏
  • 修正原Connection片段的XML语法错误
  • 保持插入内容的缩进与原文件一致,保证格式整洁
  • 添加异常处理与临时文件清理逻辑,提升鲁棒性

内容的提问来源于stack exchange,提问作者Denrie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 15:20:31