【问题标题】:Adding attributes to an XML node向 XML 节点添加属性
【发布时间】:2009-05-19 11:17:17
【问题描述】:

如何动态创建xml文件,结构如下?

<Login>
  <id userName="Tushar" passWord="Tushar">
      <Name>Tushar</Name>
      <Age>24</Age>
  </id>
</Login>

我无法在 id 标记内创建属性(即 userName="" 和 passWord="")。

我在 Windows 应用程序中使用 C#。

您可能需要的一些重要命名空间是

using System.Xml;
using System.IO;

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    id 并不是真正的根节点:Login 是。

    这应该只是使用XmlElement.SetAttribute 指定属性(不是标签,顺便说一句)的情况。不过,您尚未指定如何创建文件 - 无论您使用的是 XmlWriter、DOM 还是任何其他 XML API。

    如果您能举例说明您所获得的代码不起作用,那将很有帮助。同时,这里有一些代码可以创建您描述的文件:

    using System;
    using System.Xml;
    
    class Test
    {
        static void Main()
        {
            XmlDocument doc = new XmlDocument();
            XmlElement root = doc.CreateElement("Login");
            XmlElement id = doc.CreateElement("id");
            id.SetAttribute("userName", "Tushar");
            id.SetAttribute("passWord", "Tushar");
            XmlElement name = doc.CreateElement("Name");
            name.InnerText = "Tushar";
            XmlElement age = doc.CreateElement("Age");
            age.InnerText = "24";
    
            id.AppendChild(name);
            id.AppendChild(age);
            root.AppendChild(id);
            doc.AppendChild(root);
    
            doc.Save("test.xml");
        }
    }
    

    【讨论】:

      【解决方案2】:

      还有一种方法可以为XmlNode 对象添加属性,这在某些情况下很有用。

      我在msdn.microsoft.com 上找到了这个其他方法。

      using System.Xml;
      
      [...]
      
      //Assuming you have an XmlNode called node
      XmlNode node;
      
      [...]
      
      //Get the document object
      XmlDocument doc = node.OwnerDocument;
      
      //Create a new attribute
      XmlAttribute attr = doc.CreateAttribute("attributeName");
      attr.Value = "valueOfTheAttribute";
      
      //Add the attribute to the node     
      node.Attributes.SetNamedItem(attr);
      
      [...]
      

      【讨论】:

        【解决方案3】:

        构造 XML 的最新且被认为是最好的方法是使用 LINQ to XML:

        using System.Xml.Linq
        
               var xmlNode =
                    new XElement("Login",
                                 new XElement("id",
                                     new XAttribute("userName", "Tushar"),
                                     new XAttribute("password", "Tushar"),
                                     new XElement("Name", "Tushar"),
                                     new XElement("Age", "24")
                                 )
                    );
               xmlNode.Save("Tushar.xml");
        

        假设这种编码方式应该更容易,因为代码与输出非常相似(上面 Jon 的示例没有)。但是,我发现在编写这个相对简单的示例时,我很容易在你必须在其中导航的大量逗号之间迷路。 Visual Studio 的代码自动间距也无济于事。

        【讨论】:

          【解决方案4】:

          您可以使用类XmlAttribute

          例如:

          XmlAttribute attr = xmlDoc.CreateAttribute("userName");
          attr.Value = "Tushar";
          
          node.Attributes.Append(attr);
          

          【讨论】:

          • 你能解释一下吗?
          【解决方案5】:

          如果您序列化您拥有的对象,您可以通过在您希望指定为属性的每个属性上使用“System.Xml.Serialization.XmlAttributeAttribute”来执行类似的操作模型,在我看来要容易得多:

          [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
          public class UserNode
          {
              [System.Xml.Serialization.XmlAttributeAttribute()]
              public string userName { get; set; }
          
              [System.Xml.Serialization.XmlAttributeAttribute()]
              public string passWord { get; set; }
          
              public int Age { get; set; }
              public string Name { get; set; }         
           }
          
           public class LoginNode 
           {
              public UserNode id { get; set; }
           }
          

          然后你只需将一个名为“Login”的 LoginNode 实例序列化为 XML,就是这样!

          Here 您有一些示例可以序列化和反对 XML,但我建议创建一个扩展方法以便可重用于其他对象。

          【讨论】:

          • 如果您尝试添加属性的节点不是对象,而是字符串,您会怎么做?