Reputation: 1422
How do you create a standalone XML node in .NET?
I have an XMLElement type that I'm trying to set a value to, but since the constructor for that class is protected, it won't let me do it.
This is what I'm currently doing:
XmlDocument xmldoc = new XmlDocument();
XmlElement foo = xmldoc.CreateElement("", "foo"); ;
XmlElement bar = xmldoc.CreateElement("", "bar"); ;
Is there a better way to do this?
Upvotes: 0
Views: 735
Reputation: 707
you can try this
public XElement ToXml()
{
XElement element = new XElement("Song",
new XElement("", "foo"),
new XElement("", "bar"));
return element;
}
Upvotes: 0
Reputation: 950
Are you on .NET 3.5 or later?
using System.Xml.Linq;
var element = new XElement("foo", "bar");
Console.WriteLine(element.ToString());
Output:
<foo>bar</foo>
Upvotes: 0
Reputation: 5359
If you use XElement from System.Xml.Linq instead of the old XmlElement from System.Xml it allows you to do that very easily:
new XElement("foo")
Upvotes: 2
Reputation: 2793
I've done this in the past:
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
XmlElement fundsElement = doc.CreateElement("funds");
doc.AppendChild(fundsElement);
Upvotes: 0