【问题标题】:How to put attributes via XElement如何通过 XElement 放置属性
【发布时间】:2011-07-01 03:21:21
【问题描述】:

我有这个代码:

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.

如何向Conn 添加属性?我想添加我标记为cmets的属性,但是如果我在定义EcnAdminConf之后尝试在Conn上设置属性,它们是不可见的。

我想以某种方式设置它们,使 XML 看起来像这样:

<Type>
  <Connections>
    <Conn ServerName="FAXSERVER\SQLEXPRESS" DataBase="SPM_483000" /> 
    <Conn ServerName="FAXSERVER\SQLEXPRESS" DataBase="SPM_483000" /> 
  </Connections>
  <UDLFiles /> 
</Type>

【问题讨论】:

    标签: c# xml linq-to-xml


    【解决方案1】:

    XElement的构造函数中添加XAttribute,点赞

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

    你也可以通过构造函数添加多个属性或元素

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

    或者你可以使用XElement的Add-Method来添加属性

    XElement element = new XElement("Conn");
    XAttribute attribute = new XAttribute("Server", comboBox1.Text);
    element.Add(attribute);
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    相关资源
    最近更新 更多