Regex Replace

Xml dönüşümleri için regex kullanabiliriz. Aşağıdaki örnekte Regex.Replace metodu ile old.xml, new.xml’e dönüştürülmektedir. Her “Row” etiketine “E” özelliği eklenmektedir.

old.xml

<Rows>
  <Row A="73" B="2" C="0" D="3" />
  <Row A="140" B="3" C="1" D="2" />
  <Row A="129" B="2" C="2" D="2" />
  <Row A="255" B="4" C="3" D="10" />
  <Row A="334" B="2" C="4" D="48" />
</Rows>

new.xml

<Rows>
  <Row A="73" B="2" C="0" E="0" D="3" />
  <Row A="140" B="3" C="1" E="0" D="2" />
  <Row A="129" B="2" C="2" E="0" D="2" />
  <Row A="255" B="4" C="3" E="0" D="10" />
  <Row A="334" B="2" C="4" E="0" D="48" />
</Rows>

Program.cs

using System;
using System.IO;
using System.Text.RegularExpressions;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var oldXml = File.ReadAllText("old.xml");

            var newXml = Transform(oldXml);

            File.WriteAllText("new.xml", newXml);

            Console.WriteLine("Done.");

            Console.ReadKey();
        }

        private static string Transform(string xml)
        {
            var newXml = Regex.Replace(xml,
                                      "C=\"(?<td>.*?)\"",
                                      (m) =>
                                      {
                                          var td = m.Groups["td"].Value.Trim();

                                          return "C=\"" + td + "\" E=\"0\"";
                                      });

            return newXml;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *