将属性添加到XML节点

时间:2009-05-19 11:17:18

标签: c# xml

如何动态创建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;

5 个答案:

答案 0 :(得分:77)

id并不是根节点:Login是。

应该只是使用XmlElement.SetAttribute指定属性(而不是标签,顺便说一句)的情况。您尚未指定如何创建文件 - 无论您使用的是XmlWriter,还是使用任何其他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");
    }
}

答案 1 :(得分:30)

构建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的代码自动间隔也无济于事。

答案 2 :(得分:28)

还有一种方法可以向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 :(得分:1)

您可以使用类 XmlAttribute

例如:

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

node.Attributes.Append(attr);

答案 4 :(得分:0)

如果序列化所拥有的对象,则可以对要在属性中指定为属性的每个属性使用“ 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,但是我建议创建一个扩展方法,以便可用于其他对象。

相关问题