用c#替换xml值

时间:2015-05-13 10:36:01

标签: c# xml

我有一个xml,我想用c#重写它,用不同的vaule转换它,这里是旧的xml:

    <Connection ConnectionID="106359" From_PhraseID="1" To_PhraseID="tg1c8p-jgg-dbh-b4l-hir5cpla7_nl" />
    <Connection ConnectionID="106360" From_PhraseID="tg1c8p-jgg-dbh-b4l-hir5cpla7_nl" To_PhraseID="tg0if2-jc8-k6i-spg-2tof46ftr_nl" />
    <Connection ConnectionID="106361" From_PhraseID="tg1c8p-jgg-dbh-b4l-hir5cpla7_nl" To_PhraseID="4trq50-2h0-kqc-9ku-bm8f4cte7_nl" />
    <Connection ConnectionID="106362" From_PhraseID="tg1c8p-jgg-dbh-b4l-hir5cpla7_nl" To_PhraseID="1fpspg-tmq-7ln-a9b-3mr3962ca_nl" />
    <Connection ConnectionID="106358" From_PhraseID="tg0if2-jc8-k6i-spg-2tof46ftr_nl" To_PhraseID="jmrgi1-dst-kt6-roo-lrahuk6tj_nl" />
    <Connection ConnectionID="106373" From_PhraseID="4trq50-2h0-kqc-9ku-bm8f4cte7_nl" To_PhraseID="97bngg-ggb-k8l-ggf-qnre46ckq_nl" />
    <Connection ConnectionID="106376" From_PhraseID="1fpspg-tmq-7ln-a9b-3mr3962ca_nl" To_PhraseID="bqgccm-55n-iur-061-27obhegve_nl" />

和新的xml应该是:

<Connection ConnectionID="106359" From_PhraseID="0" To_PhraseID="1" />
<Connection ConnectionID="106360" From_PhraseID="1" To_PhraseID="2" />
<Connection ConnectionID="106361" From_PhraseID="1" To_PhraseID="3" />
<Connection ConnectionID="106362" From_PhraseID="1" To_PhraseID="4" />
<Connection ConnectionID="106358" From_PhraseID="2" To_PhraseID="6" />
<Connection ConnectionID="106373" From_PhraseID="3" To_PhraseID="7" />
<Connection ConnectionID="106376" From_PhraseID="4" To_PhraseID="5" />

任何想法如何在c#中编写它,我在这里开始,这段代码可以加载旧的xml获取c#中的所有旧值,但是如何更改值

     public class Dialogs{
            public Dictionary<string, Connection> Connections = new Dictionary<string, Connection>();
        }
    public class Connection
    {
        public string ConnectionID = null;
        public string FromPhraseID = null;
        public string ToPhraseID = null;
    }
    List<Connection> connectionsList = new List<Connection>();
            Dialogs resultDialog = new Dialogs();

            // Document

            XmlDocument xml = new XmlDocument();
            TextAsset asset = (TextAsset)Resources.Load("Dialogs/online"); 
            xml.LoadXml(asset.text);
// Connections

        XmlNodeList connections = xml.GetElementsByTagName("Connection");

        foreach (XmlNode connectionNode in connections)
        {
            Connection connection = NodeToConnection(connectionNode);
            connectionsList.Add(connection);

            if (connection != null)
            AddOrUpdateList(resultDialog.FromLists, connection);

        }
private Connection NodeToConnection(XmlNode node)
    {
        Connection connection = new Connection();

        connection.ConnectionID = node.Attributes["ConnectionID"].Value;
        connection.FromPhraseID = node.Attributes["From_PhraseID"].Value;
        connection.ToPhraseID = node.Attributes["To_PhraseID"].Value;

        return connection;
    }

    private void AddOrUpdateList(Dictionary<string, List<Connection>> dic, Connection con)
    {
        if (dic.ContainsKey(con.FromPhraseID))
            dic[con.FromPhraseID].Add(con);
        else        
            dic.Add(con.FromPhraseID, new List<Connection>(new Connection[] {con}));        
    }

3 个答案:

答案 0 :(得分:1)

请尝试以下代码。我用字典来存储替换值

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

namespace ConsoleApplication28
{
    class Program
    {
        static void Main(string[] args)
        {
            string input =
                "<Connection ConnectionID=\"106359\" From_PhraseID=\"1\" To_PhraseID=\"tg1c8p-jgg-dbh-b4l-hir5cpla7_nl\" />" +
                "<Connection ConnectionID=\"106360\" From_PhraseID=\"tg1c8p-jgg-dbh-b4l-hir5cpla7_nl\" To_PhraseID=\"tg0if2-jc8-k6i-spg-2tof46ftr_nl\" />" +
                "<Connection ConnectionID=\"106361\" From_PhraseID=\"tg1c8p-jgg-dbh-b4l-hir5cpla7_nl\" To_PhraseID=\"4trq50-2h0-kqc-9ku-bm8f4cte7_nl\" />" +
                "<Connection ConnectionID=\"106362\" From_PhraseID=\"tg1c8p-jgg-dbh-b4l-hir5cpla7_nl\" To_PhraseID=\"1fpspg-tmq-7ln-a9b-3mr3962ca_nl\" />" +
                "<Connection ConnectionID=\"106358\" From_PhraseID=\"tg0if2-jc8-k6i-spg-2tof46ftr_nl\" To_PhraseID=\"jmrgi1-dst-kt6-roo-lrahuk6tj_nl\" />" +
                "<Connection ConnectionID=\"106373\" From_PhraseID=\"4trq50-2h0-kqc-9ku-bm8f4cte7_nl\" To_PhraseID=\"97bngg-ggb-k8l-ggf-qnre46ckq_nl\" />" +
                "<Connection ConnectionID=\"106376\" From_PhraseID=\"1fpspg-tmq-7ln-a9b-3mr3962ca_nl\" To_PhraseID=\"bqgccm-55n-iur-061-27obhegve_nl\" />";

            input = "<Root>" + input + "</Root>";
            StringReader reader = new StringReader(input);
            XDocument doc = XDocument.Load(reader);

            int value = 1;
            Dictionary<string, int> dict = new Dictionary<string, int>();
            foreach (XElement connection in doc.Root.Elements("Connection"))
            {
                string fromAttr = connection.Attribute("From_PhraseID").Value;
                if (!dict.ContainsKey(fromAttr))
                {
                    dict.Add(fromAttr, value++);
                }
                string toAttr = connection.Attribute("To_PhraseID").Value;
                if (!dict.ContainsKey(toAttr))
                {
                    dict.Add(toAttr, value++);
                }
            }
            foreach (XElement connection in doc.Root.Elements("Connection"))
            {
                string fromAttr = connection.Attribute("From_PhraseID").Value;
                connection.Attribute("From_PhraseID").Value = dict[fromAttr].ToString();
                string toAttr = connection.Attribute("To_PhraseID").Value;
                connection.Attribute("To_PhraseID").Value = dict[toAttr].ToString();
            }
        }
    }
}

答案 1 :(得分:0)

使用属性设置器?

您按node.Attributes["ConnectionID"].Value获取了价值,因此您可以按以下方式设置:

node.Attributes["ConnectionID"].Value = "new value"

如果可以的话,我强烈建议使用LINQ to XML(XDocument)而不是旧的XmlDocument API。

在这种情况下,使用XmlSerializer将XML反序列化为Connection对象,进行更改并序列化回XML,甚至可能更有意义(并使用更少的代码)。

目前还不清楚你的重编号逻辑是什么。我已经创建了一个使用LINQ to XML执行此操作的示例,并按照它们看到的顺序对Phrase ID进行编号:

public class ConnectionRenumberer
{
    private List<string> phraseIds;

    public string RenumberConnections(string xml)
    {
        phraseIds = new List<string>();

        var doc = XDocument.Parse(xml);

        foreach (var connection in doc.Descendants("Connection"))
        {
            var from = connection.Attribute("From_PhraseID");
            from.Value = NewPhraseId(from.Value);

            var to = connection.Attribute("To_PhraseID");
            to.Value = NewPhraseId(to.Value);                    
        }

        return doc.ToString();
    }

    private string NewPhraseId(string value)
    {
        var index = phraseIds.IndexOf(value);

        if (index == -1)
        {
            index = phraseIds.Count;
            phraseIds.Add(value);
        }

        return index.ToString();
    }
}

这是一个相当天真的解决方案。如果输入xml很大,phraseIds会更好地替换为Dictionary

答案 2 :(得分:0)

我使用LINQ to XML。

这是一个可以为一个元素执行所需操作的示例。我会让你从那里拿走它。

static void Main(string[] args)
        {
            try
            {
                string rootXml = "<Root><Connection ConnectionID=\"106359\" From_PhraseID=\"1\" To_PhraseID=\"tg1c8p-jgg-dbh-b4l-hir5cpla7_nl\"></Connection><Connection ConnectionID=\"106360\" From_PhraseID=\"tg1c8p-jgg-dbh-b4l-hir5cpla7_nl\" To_PhraseID=\"tg0if2-jc8-k6i-spg-2tof46ftr_nl\"></Connection><Connection ConnectionID=\"106361\" From_PhraseID=\"tg1c8p-jgg-dbh-b4l-hir5cpla7_nl\" To_PhraseID=\"4trq50-2h0-kqc-9ku-bm8f4cte7_nl\"></Connection><Connection ConnectionID=\"106362\" From_PhraseID=\"tg1c8p-jgg-dbh-b4l-hir5cpla7_nl\" To_PhraseID=\"1fpspg-tmq-7ln-a9b-3mr3962ca_nl\"></Connection><Connection ConnectionID=\"106358\" From_PhraseID=\"tg0if2-jc8-k6i-spg-2tof46ftr_nl\" To_PhraseID=\"jmrgi1-dst-kt6-roo-lrahuk6tj_nl\"></Connection><Connection ConnectionID=\"106373\" From_PhraseID=\"4trq50-2h0-kqc-9ku-bm8f4cte7_nl\" To_PhraseID=\"97bngg-ggb-k8l-ggf-qnre46ckq_nl\"></Connection><Connection ConnectionID=\"106376\" From_PhraseID=\"1fpspg-tmq-7ln-a9b-3mr3962ca_nl\" To_PhraseID=\"bqgccm-55n-iur-061-27obhegve_nl\"></Connection></Root>";

                XElement root = XElement.Load((new StringReader(rootXml)), LoadOptions.None);

                root.Descendants().Where(i => i.Attribute("To_PhraseID").Value == "tg1c8p-jgg-dbh-b4l-hir5cpla7_nl")
                                    .ToList()
                                    .ForEach(i => i.SetAttributeValue("To_PhraseID", "MYNEWID"));

                var x = root.ToString();
            }
            catch (Exception ex)
            {

            }
        }