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>
3
  • 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? Commented Nov 27, 2019 at 0:39
  • Does this answer your question? How to put attributes via XElement Commented Nov 27, 2019 at 7:25
  • @juharr I put Anu Viswan's answer in a foreach loop. It is working with many id's Commented Nov 27, 2019 at 19:05

1 Answer 1

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)));
Sign up to request clarification or add additional context in comments.

1 Comment

That's it! I see you added .Value too. Thanks!

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.