I'm trying to write out all matches found using a regex with the code below:

  var source = "<Content><link><a xlink:href=\"tcm:363-48948\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">Read more</a></link><links xlink:href=\"tcm:362-65596\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"/></Content>";
  var tridionHref = new Regex("tcm:([^\"]*)");
  var elem = XElement.Parse(source);

  XNamespace xlink = "http://www.w3.org/1999/xlink";

  if (tridionHref.IsMatch(elem.ToString()))
  {
      foreach (var Id in elem.Elements().Where(x => x.Attribute(xlink + "href") != null))
      {
          Console.WriteLine(Id.Attribute(xlink + "href").Value); //For testing
          Id.Attribute(xlink + "href").Value = Id.Attribute(xlink + "href").Value.Replace("value1", "value2"); //Just to show you an example 
      }
  }

My console window outputs tcm:362-65596 but not tcm:363-48948. It looks like the code doesn't see the value of xlink:href inside my <a> tag as an attribute? Can anyone point me in the right direction? I need to match ALL instances of tcm:([^\"]*).

有帮助吗?

解决方案 2

I've got it working. I didn't need a regex I just needed to get the Descendants instead inside my for loop. foreach (var Id in elem.Descendants().Where(x => x.Attribute(xlink + "href") != null))

其他提示

The problem is you are not looking in the right place. Your elem.Elements is looking at the link element and the links element. Only one of these has the attribute that you are looking for. You'll need to select the elements you want to check more precisely before looking for the right attribute.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top