C# 向 XML 节点添加属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/882143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:16:07  来源:igfitidea点击:

Adding attributes to an XML node

c#xml

提问by

How can I create an xml file dynamically, with the following structure?

如何使用以下结构动态创建 xml 文件?

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

I am not able to create the attributes inside the idtag (i.e. userName="" and passWord="").

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

I am using C# in a windows application.

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

Some Important namespace that you might require is

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

using System.Xml;
using System.IO;

回答by Jon Skeet

Well idisn't really the root node: Loginis.

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

It should just be a case of specifying the attributes (not tags, btw) using XmlElement.SetAttribute. You haven't specified how you're creating the file though - whether you're using XmlWriter, the DOM, or any other XML API.

它应该只是使用XmlElement.SetAttribute. 不过,您还没有指定创建文件的方式——是使用 XmlWriter、DOM 还是任何其他 XML API。

If you could give an example of the code you've got which isn't working, that would help a lot. In the meantime, here's some code which creates the file you described:

如果你能给出一个你所得到的代码不起作用的例子,那会很有帮助。同时,这里有一些代码可以创建您描述的文件:

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

回答by Dabblernl

The latest and supposedly greatest way to construct the XML is by using LINQ to XML:

构造 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");

Supposedly this way of coding should be easier, as the code closely resembles the output (which Jon's example above does not). However, I found that while coding this relatively easy example I was prone to lose my way between the cartload of comma's that you have to navigate among. Visual studio's auto spacing of code does not help either.

据说这种编码方式应该更容易,因为代码与输出非常相似(Jon 上面的例子没有)。但是,我发现在编写这个相对简单的示例时,我很容易在您必须导航的逗号购物车之间迷失方向。Visual Studio 的代码自动间距也无济于事。

回答by Vito Gentile

There is also a way to add an attribute to an XmlNodeobject, that can be useful in some cases.

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

I found this other method on msdn.microsoft.com.

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

[...]

回答by Jorge Cruz

You can use the Class XmlAttribute.

您可以使用XmlAttribute类。

Eg:

例如:

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

node.Attributes.Append(attr);

回答by Mauro Bilotti

If you serialize the object that you have, you can do something like this by using "System.Xml.Serialization.XmlAttributeAttribute" on every property that you want to be specified as an attribute in your model, which in my opinion is a lot easier:

如果您序列化您拥有的对象,您可以通过在您想要指定为模型中的属性的每个属性上使用“ 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; }
 }

Then you just serialize to XML an instance of LoginNode called "Login", and that's it!

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

Hereyou have a few examples to serialize and object to XML, but I would suggest to create an extension method in order to be reusable for other objects.

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