【问题标题】:for each word (where another word in section is 'something')对于每个单词(部分中的另一个单词是“某物”)
【发布时间】:2013-05-17 09:06:31
【问题描述】:

我不确定这是否可能,但是...

我有一大段文本(kml 格式,基本上是 xml),它包含看起来像这样的代码部分(大约 75 个)

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

我需要做的是,在每个 *code 不同的地方设置 *bgcolor,一旦我有了 *code,我就可以在我的数据库中查看并分配正确的颜色。

我可以使用正则表达式来获取以“MSOA+4chars”开头的每个*代码,但我将如何编辑它上面的颜色代码?

干杯

【问题讨论】:

    标签: c# xml string kml


    【解决方案1】:

    如果是 XML 那么你可以使用 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");
    

    相关:Reading in XML/KML files using C#

    【讨论】:

      【解决方案2】:

      这是一个使用正则表达式的解决方案。此表达式的匹配项同时捕获示例中的 COLOR 标记和 TH 标记。

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

      第一个捕获组包含 4 位 MSOA 代码。然后,您可以用具有所需更新值的新标签替换整个匹配项。这是我在 LINQPad 中测试的 C# 示例。

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

      【讨论】:

        猜你喜欢
        • 2020-03-22
        • 1970-01-01
        • 2020-09-11
        • 1970-01-01
        • 1970-01-01
        • 2021-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多