Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

c# - How to put attributes via XElement

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="FAXSERVERSQLEXPRESS" DataBase="SPM_483000" /> 
    <Conn ServerName="FAXSERVERSQLEXPRESS" DataBase="SPM_483000" /> 
  </Connections>
  <UDLFiles /> 
</Type>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...