1

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>
1
  • LINQ is query language. It is designed for retrieving values from a data source, not modifying documents. While it is certainly possible using LINQ, it would hardly be efficient or clear. Commented Sep 17, 2019 at 17:21

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.