添加属性的XML节点 [英] Adding attributes to an XML node
问题描述
如何动态创建一个XML文件,具有以下结构
<登录与GT;
<编号的userName =图莎尔密码=图莎尔>
<名称>&图莎尔LT; /名称>
<年龄> 24 LT; /年龄>
< / ID>
< /登录>
我不能够创建 ID里面的属性
标记(就是用户名=和密码=)。
我使用C#在Windows应用程序。
,你可能需要一些重要的命名空间为
使用的System.Xml;
:使用System.IO;
好 ID
是不是真的根节点:登录
是
这应该只是一个案例指定使用 的XmlElement属性(不标记,顺便说一句)。的setAttribute
。您还没有指定如何你虽然创建文件 - 无论你使用的XmlWriter,DOM的,或其他任何XML API
如果你可以给一个比如你有未使用的代码,这将有很大的帮助的。在此期间,这里的一些代码,创建您所描述的文件:
使用系统;
使用的System.Xml;
类测试
{
静态无效的主要()
{
XmlDocument的DOC =新的XmlDocument();
的XmlElement根= doc.CreateElement(登录);
的XmlElement ID = doc.CreateElement(ID);
id.SetAttribute(username的,图莎尔);
id.SetAttribute(密码,图莎尔);
的XmlElement名称= doc.CreateElement(名称);
name.InnerText =图莎尔;
XmlElement的年龄= doc.CreateElement(时代);
age.InnerText =24;
id.AppendChild(名);
id.AppendChild(年龄);
root.AppendChild(ID);
doc.AppendChild(根);
doc.Save(的test.xml);
}
}
How can I create an xml file dynamically, with the following structure?
<Login>
<id userName="Tushar" passWord="Tushar">
<Name>Tushar</Name>
<Age>24</Age>
</id>
</Login>
I am not able to create the attributes inside the id
tag (i.e. userName="" and passWord="").
I am using C# in a windows application.
Some Important namespace that you might require is
using System.Xml;
using System.IO;
Well id
isn't really the root node: Login
is.
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.
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");
}
}
这篇关于添加属性的XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!