user222427
user222427

Reputation:

C# how to create a custom xml document

I'm really just trying to create a custom xml document for simple configuration processing.

        XmlDocument xDoc = new XmlDocument();
        string[] NodeArray = { "Fruits|Fruit", "Vegetables|Veggie"};
        foreach (string node in NodeArray)
        {
            XmlNode xmlNode = xDoc.CreateNode(XmlNodeType.Element,node.Split('|')[0],null);
            //xmlNode.Value = node.Split('|')[0];
            xmlNode.InnerText = node.Split('|')[1];
            xDoc.DocumentElement.AppendChild(xmlNode);

        }

What i'm trying to get is this.

<?xml version="1.0" encoding="ISO-8859-1"?>
<Fruits>Fruit</Fruits>
<Vegetables>Veggie</Vegetables>

i get not set to value of an object at xDoc.DocumentElement.AppendChild(xmlNode);

Upvotes: 1

Views: 3597

Answers (2)

bizzehdee
bizzehdee

Reputation: 21023

It is not possible to have that XML structure as XML MUST have a single root element. You may want to try:

<?xml version="1.0" encoding="ISO-8859-1"?>
<items>
  <Fruits>Fruit</Fruits>
  <Vegetables>Veggie</Vegetables>
</items>

Upvotes: 0

Unfortunately, You can't make that XML structure.

All XML documents must have a single root node. You can't have more.

Try something like this

XmlDocument xDoc = new XmlDocument();

xDoc.AppendChild( xDoc.CreateElement("root"));

string[] NodeArray = { "Fruits|Fruit", "Vegetables|Veggie" };
foreach (string node in NodeArray)
{
    XmlNode xmlNode = xDoc.CreateNode(XmlNodeType.Element, node.Split('|')[0], null);
    //xmlNode.Value = node.Split('|')[0];
    xmlNode.InnerText = node.Split('|')[1];
    xDoc.DocumentElement.AppendChild(xmlNode);

}

Upvotes: 1

Related Questions