【问题标题】:Replace text inside .txt file or .xml file using loop [closed]使用循环替换.txt文件或.xml文件中的文本[关闭]
【发布时间】:2021-07-28 13:22:11
【问题描述】:

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

我尝试在 Stack Overflow 上进行大量搜索,但没有一个答案能一口气解决我的问题,而且我太缺乏经验,无法将它们全部粘合在一起。 该解决方案可以使用 XML 解析器或仅使用 .txt 文件。我希望按顺序选择的语言:Python、Java、C# 或 Scala。它不需要是一个稳健/长期的解决方案,因为它不会被依赖。

例如

<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 python c# xml txt


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    使用 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));
    
                }
            }
        }
     
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多