0

我正在用 C# 创建 XML。我想附加itemcontent. 我用 . 创建了一个 XmlNode CreateItem,但我似乎无法将它附加到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;
}
4

1 回答 1

1

您没有调用该CreateItem方法,所以它实际上并没有创建一个<item>,所以没有什么要附加的。

怎么样:

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;
}

注意var关键字。请参阅类型推断,即“隐式类型局部变量”

于 2015-05-01T09:27:27.867 回答