我正在使用C#创建XML。我想把item附加到content上。我用CreateItem创建了一个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;
}发布于 2015-05-01 09:27:27
您没有调用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关键字。参见类型推断,a.k.a “隐式局部变量”。
https://stackoverflow.com/questions/29984049
复制相似问题