通过依赖XML文件中的现有值来替换该值

时间:2018-04-08 05:32:30

标签: c# xml

这是一个示例XML文件:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="app_name">Automation Test</string>
  <string name="current_data_state_incoming_call">Incoming Call</string>
  <string name="current_data_state_outgoing_call">Outgoing Call</string>
  <string name="current_data_state_missed_call">Missed Call</string>
  <string name="current_data_state_photo">Photo</string>
  <string name="current_data_state_video">Video</string>
  <string name="current_data_state_mp3">MP3</string>
  <string name="current_data_state_voice_memo">Voice Memo</string>
  <string name="current_data_state_phone_book">Phone Book</string>
  <string name="current_data_state_phone_booksim">Phone Book(SIM)</string>
  <string name="current_data_state_etc">Etc</string>
  <string name="current_data_state_schedule">S Planner</string>

</resources>

我有一个大文件XML文件,我想根据原始值替换元素中的值。

例如,我想用另一个单词替换“拨出电话”。 我试过这段代码:

XmlDocument xdoc = new XmlDocument();
xdoc.Load("strings.xml");

XmlElement root = xdoc.DocumentElement;
XmlNodeList elemList = root.GetElementsByTagName("string");

for (int i = 0; i < elemList.Count; i++)
{
    xdoc.Save("strings.xml");

    if (elemList[i].InnerText == "Incoming Call")
    {
        // xdoc.LoadXml(File.ReadAllText("strings.xml").Replace(elemList[i].InnerText, "صندوق"));
        //   MessageBox.Show(elemList[i].InnerText);
        elemList[i].SelectSingleNode("resources/string").InnerText="مكالمات قادمة";        
        xdoc.Save("strings.xml");
    }
}

和此代码

XmlDocument xdoc = new XmlDocument();
xdoc.Load("strings.xml");

XmlNodeList aNodes = xdoc.SelectNodes("resources/string");
foreach (XmlNode node in aNodes)
{
    XmlNode child1 = node.SelectSingleNode("string");
    if(child1.InnerText == "Incoming Call")
    {
        child1.InnerText = "اتصالات قادمة";
    }
}
xdoc.Save("strings.xml");

我无法替换该值。

=================================== thanx我解决了我的问题

var root2 = new XmlDocument();
        root2.Load("strings.xml");
        var root = new XmlDocument();
        root.Load("strings2.xml");

        foreach (XmlNode e1 in root2.GetElementsByTagName("string"))
        {
            string a = e1.Attributes["name"].Value;
            foreach (XmlNode ee in root.GetElementsByTagName("string"))

            {
                string b = ee.Attributes["name"].Value;
                if (a == b)
                {
                    e1.FirstChild.Value = ee.FirstChild.Value;
                }
            }



        }
        root.Save("strings.xml");

2 个答案:

答案 0 :(得分:1)

我会使用LINQ to XML。它使各种事情比XmlDocument简单得多。以下是执行替换的完整示例(加载input.xml并撰写output.xml):

using System;
using System.Linq;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        XDocument doc = XDocument.Load("input.xml");
        ReplaceValue(doc, "Outgoing Call", "Other value");
        doc.Save("output.xml");
    }

    static void ReplaceValue(XDocument doc, string original, string replacement)
    {
        foreach (var element in doc.Descendants("string").Where(x => x.Value == original))
        {
            element.Value = replacement;
        }
    }
}

如果找不到您要替换的值,或者找到多个元素,您可以轻松更改方法以引发异常。

替换为 value 的替代方法是替换为name属性,这将是一个微不足道的变化:

static void ReplaceNamedValue(XDocument doc, string name, string replacement)
{
    foreach (var element in doc.Descendants("string")
        .Where(x => (string) x.Attribute("name") == name))
    {
        element.Value = replacement;
    }
}

然后你会这样称呼它:

ReplaceNamedValue(doc, "current_data_state_outgoing_call", "Other value");

答案 1 :(得分:-1)

您可能希望动态创建xml上的文件而不是替换。我更喜欢使用较新的Net库xml linq(XDocument)而不是旧版本的XmlDocument。以下是我将使用的代码示例:

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

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            string ident = "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources></resources>";
            XDocument doc = XDocument.Parse(ident);

            XElement resources = doc.Root;

            resources.Add(new XElement("string", new object[] {
                new XAttribute("name","app_name"),
                "Automation Test"
            }));

            resources.Add(new XElement("string", new object[] {
                new XAttribute("name","current_data_state_incoming_call"),
                "مكالمات قادمة"
            }));
        }
    }
}

以下是替换代码

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

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {

            XDocument doc = XDocument.Load(FILENAME);
            XElement resource = doc.Root;

            Dictionary<string, XElement> dict = resource.Elements()
                .GroupBy(x => (string)x.Attribute("name"), y => y)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

            if(dict.ContainsKey("app_name"))
            {
                dict["app_name"].SetValue("Automation Test");
            }

            if (dict.ContainsKey("current_data_state_incoming_call"))
            {
                dict["current_data_state_incoming_call"].SetValue("مكالمات قادمة");
            }

        }
    }
}