首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >XmlNode.AppendChild失败

XmlNode.AppendChild失败
EN

Stack Overflow用户
提问于 2015-05-01 08:53:39
回答 1查看 2.7K关注 0票数 0

我正在使用C#创建XML。我想把item附加到content上。我用CreateItem创建了一个CreateItem,但是我似乎不能将它附加到contentElement中。

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-01 09:27:27

您没有调用CreateItem方法,因此它实际上没有创建<item>,因此没有什么可追加的。

不如:

代码语言:javascript
复制
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关键字。参见类型推断,a.k.a “隐式局部变量”

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29984049

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档