PDA

Click to See Complete Forum and Search --> : Add XML Node Attribute Help..


kleptos
Apr 5th, 2003, 04:45 PM
Below is code i have to write an a node to an xml file. How can i add an attribute to the "error" node?



XmlDocument doc = new XmlDocument();
doc.Load("Errors.xml");

XmlNode node = doc.CreateNode(XmlNodeType.Element,"error",null);
XmlNode item = doc.CreateNode(XmlNodeType.Element,"date",null);
item.InnerText = DateTime.Now.ToString();
doc.DocumentElement.AppendChild(node);
node.AppendChild(item);

doc.Save("Errors.xml");



The above gives me this:
<error>
<date>4/5/2003</date>
</error>

I want this:
<error id="14">
<date>4/5/2003</date>
</error>

Lethal
Apr 5th, 2003, 04:56 PM
Here you go:


doc.DocumentElement.SetAttribute("id", "14");

or...

XmlAttribute attr = doc.CreateAttribute("id");
attr.Value = "14";
doc.DocumentElement.SetAttributeNode(attr);

kleptos
Apr 5th, 2003, 05:10 PM
Awsome, Thank you....

Now, my next issue, and i didnt explain it right, sorry, this is what i need it to do.


<errors>
<error id="12">
<message>Message Here</message>
</error>
<error id="13">
<message>Message Here</message>
</error>
</errors>


That code (which works great) gave me this

<errors id="12">
<error>
<message>Message Here</message>
</error>
<error>
<message>Message Here</message>
</error>
</errors>

Lethal
Apr 5th, 2003, 05:19 PM
All you have to do is get a reference to the node you want to append additional nodes to.


XmlNode node = doc.DocumentElement.SelectSingleNode("error");
XmlAttribute x = doc.CreateAttribute("id");
x.Value = "14";
node.Attributes.SetNamedItem(x);

kleptos
Apr 5th, 2003, 05:25 PM
Thank you so much... I am trying so hard to learn C# with XML, and this helps me alot.

Lethal
Apr 5th, 2003, 05:29 PM
no problem...i have extensive experience with xml/xslt, so if you have any questions, feel free to ask.:)