2015-05-01 40 views
0

我正在用C#創建XML。我想追加itemcontent。我創建了一個與CreateItem XmlNode,但我似乎無法將其追加到contentElementXmlNode.AppendChild失敗

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

什麼是'CreteItem',它在哪裏定義? –

+0

public xmlNode,line 5 – Eleanor

+3

出於興趣,是否有任何理由不能使用LINQ to XML?這通常是一個*多*更好的API ... –

回答

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關鍵字。參見類型推斷,又名"Implicitly Typed Local Variables"

+0

謝謝@阿薩德~~~ – Eleanor

+0

非常感謝@托馬拉克 – Eleanor