145

I have this code:

XElement EcnAdminConf = new XElement("Type",
    new XElement("Connections",
    new XElement("Conn"),
    // Conn.SetAttributeValue("Server", comboBox1.Text);
    // Conn.SetAttributeValue("DataBase", comboBox2.Text))),
    new XElement("UDLFiles")));
    // Conn.

How do I add attributes to Conn? I want to add the attributes I marked as comments, but if I try to set the attributes on Conn after defining EcnAdminConf, they are not visible.

I want to set them somehow so the XML looks like this:

<Type>
  <Connections>
    <Conn ServerName="FAXSERVER\SQLEXPRESS" DataBase="SPM_483000" /> 
    <Conn ServerName="FAXSERVER\SQLEXPRESS" DataBase="SPM_483000" /> 
  </Connections>
  <UDLFiles /> 
</Type>
CarenRose
  • 1,266
  • 1
  • 12
  • 24
Dominating
  • 2,890
  • 7
  • 25
  • 39

1 Answers1

289

Add XAttribute in the constructor of the XElement, like

new XElement("Conn", new XAttribute("Server", comboBox1.Text));

You can also add multiple attributes or elements via the constructor

new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));

or you can use the Add-Method of the XElement to add attributes

XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);
Jehof
  • 34,674
  • 10
  • 123
  • 155
  • Is it possible to build a list or array of xAttr and add them all at once? – greg Apr 17 '19 at 16:27
  • @greg you could use the .Add()-overload to pass in multiple XAttribute objects (https://learn.microsoft.com/de-de/dotnet/api/system.xml.linq.xcontainer.add?view=netframework-4.7.2#System_Xml_Linq_XContainer_Add_System_Object___) – Jehof Apr 17 '19 at 18:55