使用循环替换 .txt 文件或 .xml 文件中的文本

Replace text inside .txt file or .xml file using loop

我想将变量添加到我的文件中,以便其他程序可以读取它。每个变量名都必须是唯一的。

我尝试在 Stack Overflow 上搜索很多,但 none 的答案一次性解决了我的问题,而且我太缺乏经验无法将它们粘合在一起。 解决方案可以使用 XML 解析器或仅使用 .txt 文件。我喜欢的语言顺序为:Python、Java、C# 或 Scala。它不需要是 robust/long 术语解决方案,因为它不会被依赖。

例如

<Tag1>
     <USA></USA>
     <UK></UK>
</Tag1>
<Tag2>
     <FRA></FRA>
     <USA></USA>
</Tag2>

我想把上面的文件编辑成:

<Tag1>
     <USA>var1a</USA>
     <UK>var1b</UK>
     <FRA>var1c</FRA>
</Tag1>
<Tag2>
     <USA>var2a</USA>
     <UK>var2b</UK>
     <FRA>var2c</FRA>
</Tag2>

谢谢

使用 Java,您可以使用 FileReader 和 if/then 语句实现此目的。 首先,导入 java.io.*

import java.io.*;

然后,您将编写看起来像这样东西的代码

File XMLFile =  new File("<filepath here>");
FileReader Reader =  new FileReader(XMLFile);
ArrayList<String> Lines = new ArrayList<String>();
while(Reader.hasNextLine()){
 Lines.add(Reader.NextLine());
}

这将创建一个字符串数组列表,其中每个字符串都是文件的一行。剩下的项目就交给你了!

使用 xml linq :

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication
{
     class Program
    {
         static void Main(string[] args)
        {
            string xml = @"<Root>
                              <Tag1>
                                <USA></USA>
                                <UK></UK>
                              </Tag1>
                              <Tag2>
                                <FRA></FRA>
                                <USA></USA>
                              </Tag2>
                            </Root>";

            XDocument doc = XDocument.Parse(xml);

            List<XElement> tags = doc.Descendants().Where(x => x.Name.LocalName.StartsWith("Tag")).ToList();
            List<string> countries = tags.SelectMany(x => x.Elements().Select(y => y.Name.LocalName)).Distinct().OrderBy(x => x).ToList();

            for (int i = 0; i < tags.Count; i++)
            {
                List<XElement> children = countries.Select((x, j) => new XElement(x, "var" + (i + 1).ToString() + ((char)(((byte)'a') + j)).ToString())).ToList();
                tags[i].ReplaceWith(new XElement(tags[i].Name.LocalName, children));

            }
        }
    }
 
}