C# 向XML节点添加属性
如何使用以下结构动态创建xml文件C# 向XML节点添加属性,c#,xml,C#,Xml,如何使用以下结构动态创建xml文件 <Login> <id userName="Tushar" passWord="Tushar"> <Name>Tushar</Name> <Age>24</Age> </id> </Login> 嗯,id不是真正的根节点:Login是 它应该只是使用指定属性(不是标记,顺便说一句)的情况。但是,您还没有指定如何创建文件——无论您是使
<Login>
<id userName="Tushar" passWord="Tushar">
<Name>Tushar</Name>
<Age>24</Age>
</id>
</Login>
嗯,
id
不是真正的根节点:Login
是
它应该只是使用指定属性(不是标记,顺便说一句)的情况。但是,您还没有指定如何创建文件——无论您是使用XmlWriter、DOM还是任何其他XMLAPI
如果你能举一个例子,说明你得到的代码不起作用,那将非常有帮助。同时,下面是一些创建您描述的文件的代码:
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");
}
}
构造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的自动代码间距也没有帮助。还有一种向
XmlNode
对象添加属性的方法,在某些情况下可能很有用
我在上找到了另一种方法
您可以使用类XmlAttribute 例如:
如果序列化您拥有的对象,您可以通过对每个要在模型中指定为属性的属性使用“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,就这样
您有几个示例要序列化并将对象转换为XML,但我建议创建一个扩展方法,以便可用于其他对象 你能解释一下吗?
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);
[...]
XmlAttribute attr = xmlDoc.CreateAttribute("userName");
attr.Value = "Tushar";
node.Attributes.Append(attr);
[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; }
}