在中更改xml属性名称

Tom*_*der 4 c# xml

如何在c#中更改XElement属性名称?

因此,如果

<text align="center"> d hhdohd  </text>
Run Code Online (Sandbox Code Playgroud)

更改后的属性名称对齐到text-align

<text text-align="center> d hhdohd  </text>
Run Code Online (Sandbox Code Playgroud)

ada*_*ost 6

使用LINQ-XML,您可以删除existing属性,然后添加一个新属性.

Xml标记:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <text align="center" other="attribute">Something</text>
</root>
Run Code Online (Sandbox Code Playgroud)

码:

 XDocument doc = XDocument.Load(file);
 var element = doc.Root.Element("text");
 var attList = element.Attributes().ToList();
 var oldAtt = attList.Where(p => p.Name == "align").SingleOrDefault();
 if (oldAtt != null)
  {
   XAttribute newAtt = new XAttribute("text-align", oldAtt.Value);
   attList.Add(newAtt);
   attList.Remove(oldAtt);
   element.ReplaceAttributes(attList);
   doc.Save(file);
 }
Run Code Online (Sandbox Code Playgroud)