XDocument changes all attribute names

I have an XDocument that looks like

<root>
     <a>
          <b foo="1" bar="2" />
          <b foo="3" bar="4" />
          <b foo="5" bar="6" />
          <b foo="7" bar="8" />
          <b foo="9" bar="10" />
     </a>
</root>

I want to change the foo attribute to something else, and the attribute to something else. How can i do this? My current version (below) of the stack is full of large documents and has a terrible smell.

        string dd=LoadedXDocument.ToString();
        foreach (var s in AttributeReplacements)
            dd = dd.Replace(s.Old+"=", s.New+"=");
+3
source share
2 answers

Here is the complete XSLT solution :

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:my="my:reps"
    exclude-result-prefixes="my"
>
    <xsl:output omit-xml-declaration="yes" indent="yes"/>

    <my:replacements>
      <foo1 old="foo"/>
      <bar1 old="bar"/>
    </my:replacements>

    <xsl:variable name="vReps" select=
     "document('')/*/my:replacements/*"/>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="@*">
  <xsl:variable name="vRepNode" select=
   "$vReps[@old = name(current())]"/>

   <xsl:variable name="vName" select=
    "name(current()[not($vRepNode)] | $vRepNode)"/>

   <xsl:attribute name="{$vName}">
     <xsl:value-of select="."/>
   </xsl:attribute>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied to the provided XML document, the desired result is created :

<root>
   <a>
      <b foo1="1" bar1="2"/>
      <b foo1="3" bar1="4"/>
      <b foo1="5" bar1="6"/>
      <b foo1="7" bar1="8"/>
      <b foo1="9" bar1="10"/>
   </a>
</root>

, , . XML .

+2

StringBuilder, ( ). (, , , node?)

:

  • XDocument XmlDocument, , .
  • XSLT
  • XmlReader XmlWriter .

# 3 . # 2 XSLT, ( XSLT , , , ). # 1, , , .

XSLT Xml Reader/Writer .

# 1 , - ( XML ):

using System.Xml.Linq;
using System.Xml.XPath;

var xdoc = XDocument.Load(....);
var nav = xdoc.CreateNavigator();

foreach (repl in replacements) {
  var found = (XPathNodeIterator) nav.Evaluate("//@" + repl.OldName);

  while (found.MoveNext()) {
    var node = found.Current;
    var val = node.Value;
    node.DeleteSelf(); // Moves ref to parent.
    node.CreateAttribute("", repl.NewName, "", val);
  }
}

( ) . ( ) .

+3

Source: https://habr.com/ru/post/1741224/


All Articles