0

I am creating XML with C#. I want to append item to content. I create an XmlNode with CreateItem, but I can't seem to append it to the contentElement.

XmlDocument doc = new XmlDocument();
XmlNode contentElement = doc.CreateElement("content");
doc.AppendChild(contentElement);
contentElement.AppendChild(CreateItem);

public XmlNode CreateItem(XmlDocument doc, string hint, string type, string title, string value) {
    XmlNode item = doc.CreateElement("item");

    XmlAttribute Hint = doc.CreateAttribute("Hint");
    Hint.Value = hint;
    XmlAttribute Type = doc.CreateAttribute("Type");
    Type.Value = type;

    item.Attributes.Append(Hint);
    item.Attributes.Append(Type);

    XmlNode tit = doc.CreateElement("Title");
    tit.InnerText = title;

    item.AppendChild(tit);

    XmlNode val = doc.CreateElement("Value");
    val.InnerText = value;

    item.AppendChild(val);

    return item;
}
Tomalak
  • 332,285
  • 67
  • 532
  • 628
Eleanor
  • 569
  • 1
  • 8
  • 17

1 Answers1

1

You did not call the CreateItem method, so it did not actually create an <item>, so there was nothing to append.

How about:

public static void Main()
{
    var doc = new XmlDocument();
    var content = doc.CreateElement("content");
    doc.AppendChild(content);
    var item = CreateItem(doc, "the hint", "the type", "the title", "the value");
    content.AppendChild(item);
}

public static XmlElement CreateItem(XmlDocument doc, string hint, string type, string title, string value)
{
    var item = doc.CreateElement("item");
    item.SetAttribute("Hint", hint);
    item.SetAttribute("Type", type);
    AppendTextElement(item, "Title", title);
    AppendTextElement(item, "Value", value);
    return item;
}

public static XmlElement AppendTextElement(XmlElement parent, string name, string value)
{
    var elem = parent.OwnerDocument.CreateElement(name);
    parent.AppendChild(elem);
    elem.InnerText = value;
    return elem;
}

Note the var keyword. See Type Inference, a.k.a "Implicitly Typed Local Variables".

Tomalak
  • 332,285
  • 67
  • 532
  • 628