Krzysztof Radzimski

Pasja tworzenia

Jak zmienić nazwy węzłów i atrybutów za pomocą LINQ

17 styczeń
Opublikował Krzysztof Radzimski 17. stycznia 2010 21:19

Przy różnych konwersjach XML lub HTML przydatne okazuje się zamienianie nazw znaczników lub atrybutów. Z użyciem LINQ dla XML jest to banalnie proste.

Zmiana nazwy atrybutu

   1:  public static void EAP_RenameAttribute(this XElement x, 
   2:          string oldName, string newName) {
   3:   IEnumerable<XElement> elList = from el in x.DescendantsAndSelf()
   4:                 where el.Attribute(oldName) != null
   5:                 select el;
   6:   
   7:      foreach (XElement e in elList) {
   8:          if (e.Attribute(newName) == null) {
   9:              e.Add(new XAttribute(newName, e.Attribute(oldName).Value));
  10:              e.Attribute(oldName).Remove();
  11:          }
  12:      }
  13:  }

Zmiana nazwy elementu

   1:  public static IEnumerable<XElement> EAP_RenameAnyElement(this XElement x, string oldName, string newName) {
   2:      IEnumerable<XElement> elList = from el in x.DescendantsAndSelf()
   3:                     where el.Name.LocalName == oldName
   4:                     select el;
   5:   
   6:      List<XElement> r = new List<XElement>();
   7:      foreach (XElement e in elList) {
   8:          if (e != null) {
   9:              e.Name = XName.Get(newName, e.Name.NamespaceName);
  10:              r.Add(e);
  11:          }
  12:      }
  13:      return r;
  14:  }

Tagi: , | Kategorie: Programowanie

Wyślij link na adres e-mail | Link do tego postu | RSSRSS comment feed