Click here to Skip to main content
15,889,909 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,

I am using the following to create a simple XML document and am not getting the expected output:

C#
XmlDocument doc = new XmlDocument();

XmlNode animals = doc.CreateElement("animals");
doc.AppendChild(animals);
            
XmlNode cats = doc.CreateElement("cats");           
           
XmlAttribute countAttribute = doc.CreateAttribute("count");
countAttribute.Value = "1";
cats.Attributes.Append(countAttribute);

animals.AppendChild(cats);

rtfOutput.Text = XElement.Parse(doc.OuterXml).ToString();


I am getting the following output:

XML
<animals>
  <cats count="1" />
</animals>


What I'm really trying to get is this:
XML
<animals>
  <cats calico="count">1</cats>
</animals>


Any guidance in this would be greatly appreciated!

Thanks in advance!

What I have tried:

I have perused some of the examples at Microsoft Docs and have used Google and found many XML examples but wasn't able to find anything that would point me in the right direction... problem is, I'm not sure what I'm looking for so I most likely have seen the answer but didn't notice it!
Posted
Updated 27-Jan-21 21:02pm

You can achieve it like this:
XML
var doc = new XmlDocument();

XmlNode animals = doc.CreateElement("animals");
doc.AppendChild(animals);

XmlNode userNode = doc.CreateElement("cats");
var attribute = doc.CreateAttribute("calico");
attribute.Value = "count";

userNode.Attributes.Append(attribute);
userNode.InnerText = "1";
animals.AppendChild(userNode);
Please have a look here: Writing XML with the XmlDocument class - The complete C# tutorial[^]
 
Share this answer
 
v2
Comments
junrall 28-Jan-21 9:43am    
Thank you for your solution! Makes total sense, once I see it. And thank you for the link... I'll read through the tutorials there!
TheRealSteveJudge 28-Jan-21 10:17am    
You're welcome. Good luck!
XML
<cats calico="count">1</cats>
"cats" is a node, with the value "1"; "calico" is an attribute with the value "count".

Your code is trying to create "count" as an attribute - so it's being created that way.
Try something like:
C#
XmlNode cats = doc.CreateElement("cats");    
cats.Value = 1;       
           
XmlAttribute countAttribute = doc.CreateAttribute("calico");
countAttribute.Value = "count";
cats.Attributes.Append(countAttribute);

You may have to play with it to get the code right - I'm on a tablet and it's hard to test code so I'm relying on memory ...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900