0

Im not sure if this is possible but...

I have a large block of text (kml format, which is basically xml) it contains sections of code that look like this (around 75 of them)

<color>ff0780dd</color> *bgcolor
<th>MSOA11CD</th> *code
<td>E02001618</td>

what i need to do is, set the *bgcolor where each *code is different, once i have the *code i can look in my DB and assign the correct color.

I could use regex to get each *code that starts with "MSOA+4chars" but how would i then edit the color code above it?

Cheers

Nixdorf
  • 61
  • 8

2 Answers2

0

If it is XML then you can use LINQ to XML

// find nodes 
XNamespace ns = "url....";
var doc = XDocument.Load("Test.xml");
var items =( from item in doc.Descendants(ns+"Document").Descendants(ns+"Item")
            where CheckItem(item.Element(ns+"th").Value)
            select item).ToList();
// update nodes 
for (int i = 0; i < items.Count(); i++)
{
    items[i].SetElementValue(ns + "color", GetColor(items[i].Value));
}
// saving updated xml 
doc.Save("Test.xml");

Related : Reading in XML/KML files using C#

Community
  • 1
  • 1
Damith
  • 62,401
  • 13
  • 102
  • 153
0

Here is a solution using a regex. A match from this expression captures both the COLOR tags and the TH tags from your example.

<color>[^<]+</color>\s*<th>MSOA(\w+)</th>

The first capture group contains the 4 digit MSOA code. Your can then replace the whole match with new tags that have the desired updated values. Here is an example in C# that I tested in LINQPad.

void Main() {
    string inputString = @"
        <color>ff0780dd</color>
        <th>MSOA11CD</th>
        <td>E02001618</td>";
    string result = Regex.Replace(inputString, @"<color>[^<]+</color>\s*<th>MSOA(\w+)</th>", new MatchEvaluator(ComputeReplacement), RegexOptions.IgnoreCase | RegexOptions.Multiline);
    Console.Out.WriteLine(result);
}

public String ComputeReplacement(Match m) {
    const int GRP_MSOA_CODE = 1;
    string msoaCode = m.Groups[GRP_MSOA_CODE].Value;
    string colorCode = "SOME COLOR CODE"; //Get the code to use between the "color" tags from your DB.
    return String.Format("<color>{0}</color>\n<th>MSOA{1}</th>", colorCode, msoaCode);
}
Francis Gagnon
  • 3,545
  • 1
  • 16
  • 25