0

I am reading and building a new xml string in C# like this:

private string XmlString
{
    get
    {
        if (my_xml.Nodes().Count() > 0)
        {
            var param = new XElement("param");

            var ids = my_xml.Elements("ID").ToList();
            foreach (var id in ids)
            {
                param.Add(new XElement("ids", new XElement("ID", id.Value)));
            }
            return param.ToString();
        }
        return null;
    }
}

I get a xml string which is something like:

<param>
    <ids>
        <id>2</id>
    </ids>
</param>

How should look like my method to get a xml string like this one with = :

  <param>
        <ids id="2"/>
  </param>
Hrvoje T
  • 3,365
  • 4
  • 28
  • 41
  • What if `my_xml` as more than one ID element? Where do you expect to set all the id attributes? Should there be more than one `ids` element in that case? – juharr Nov 27 '19 at 00:39
  • Does this answer your question? [How to put attributes via XElement](https://stackoverflow.com/questions/5063936/how-to-put-attributes-via-xelement) – xdtTransform Nov 27 '19 at 07:25
  • @juharr I put Anu Viswan's answer in a foreach loop. It is working with many id's – Hrvoje T Nov 27 '19 at 19:05

1 Answers1

3

You could use SetAttributeValue for adding an attribute.

var xElement = new XElement("ids"); 
xElement.SetAttributeValue("id",id.Value);
param.Add(xElement);

Alternatively, you could also use an override of XElement Constructor

param.Add(new XElement("ids", new XAttribute("id", id.Value)));
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51