Andy Rehn
Andy Rehn

Reputation: 139

Replace XML-element with LINQ to XML

I would like to solve the following problem using LINQ to XML, if possible. Using LINQ to XML might not be the suitable way to solve a problem like this? If not, what is the best technique to use? All elements like this:

<Name>XXX</Name>

sholud be replaced with:

<Attribute name="Name">XXX</Attribute>

in the following XML?

  <Object type="SignalGroup">
    <Name>General</Name>
    <Object type="Signal">
      <Name>Input</Name>
      <Attribute name="Description">This is a public object.</Attribute>
    </Object>
    <Object type="Signal">
      <Name>PublicName</Name>
      <Attribute name="ToolTitle">Public name</Attribute>
      <Attribute name="Description">This is a public object.</Attribute>
    </Object>
  </Object>

The desired result is:

  <Object type="SignalGroup">
    <Attribute name="Name">General</Attribute>
    <Object type="Signal">
      <Attribute name="Name">Input</Attribute>
      <Attribute name="Description">This is a public object.</Attribute>
    </Object>
    <Object type="Signal">
      <Attribute name="Name">PublicName</Attribute>
      <Attribute name="ToolTitle">Public name</Attribute>
      <Attribute name="Description">This is a public object.</Attribute>
    </Object>
  </Object>

Upvotes: 1

Views: 357

Answers (1)

Charles Mager
Charles Mager

Reputation: 26223

You want to query all elements with the name Name and either rename that element and add the missing attribute, or replace them with an Attribute element that has the value of that element.

So either this:

foreach (var name in doc.Descendants("Name"))
{
    name.Name = "Attribute";
    name.Add(new XAttribute("name", "Name"));
}

Or this. Note the ToList is required here as replacing the element would break the enumeration as you'll have removed the current element from the document.

foreach (var name in doc.Descendants("Name").ToList())
{
    var attr = new XElement("Attribute",
        new XAttribute("name", "Name"), name.Value);
    name.ReplaceWith(attr);
}

See this fiddle for a demo.

Upvotes: 2

Related Questions