簡體   English   中英

使用子節點Xml和C#添加新元素

[英]Adding new element with child nodes Xml and C#

我有一個我正在編寫的Windows窗體應用程序,我想創建一個xml文件並向其添加數據。

代碼如下。

 xmlFile = new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                    new XComment("XML File for storing " + RootName));
xmlFile.Add(new XElement(RootName));

// Loop through the list and create a new element for each item in the list
foreach (Contact c in contactsList)
{
    try
    {
        xmlFile.Add(new XElement("Contact",
            new XElement("Name", c.Name),
            new XElement("Email", c.EmailAddress),
            new XElement("Mobile Number", c.MobileNumber),
            new XElement("Mobile Carrier", c.sMobileCarrier)
            )
        );
    }
    catch
    {
        MessageBox.Show("ERROR WITH NEW ELEMENTS");
    }
}
xmlFile.Save(FileName);

當我運行程序時,try塊拋出並出錯,我收到消息框錯誤。 當我調試時,該程序說該例外與以下內容有關:

The ' ' character, hexadecimal value 0x20, cannot be included in a name.

我不確定這意味着什么,因為我檢查了傳入的所有值,直到進入點,那里有一些東西。

我在xmlFile.Add()語句中缺少一個參數嗎?

最后一個問題,當我在創建XDocument對象后插入Root元素時,在文件中它出現為<Contacts /> ,我希望它是關閉的根標記。

如何插入起始標記,然后當我最后保存時,它會附加結束標記?

謝謝

更新---------------------感謝MarcinJuraszek,我能夠超越該異常被拋出,但現在我收到此錯誤:

This operation would create an incorrectly structured document.

任何想法是什么意思或是什么導致它?

錯誤消息是明確的:XML元素名稱不能包含空格。 你正試圖這樣做:

        new XElement("Mobile Number", c.MobileNumber),
        new XElement("Mobile Carrier", c.sMobileCarrier)

將這些行更改為不包含空格,它應該可以工作。 例如

        new XElement("MobileNumber", c.MobileNumber),
        new XElement("MobileCarrier", c.sMobileCarrier)

如何插入起始標記,然后當我最后保存時,它會附加結束標記?

不要擔心開始/關閉標簽。 XElement.Save方法將處理這個問題。

更新

這里的第二個問題是,您正在嘗試使用多個根元素創建文檔。 這是因為您不是將新內容添加到根XElement而是嘗試將其直接添加到XDocument實例中。

試試以下:

    xmlFile.Root.Add(new XElement("Contact",
        new XElement("Name", c.Name),
        new XElement("Email", c.EmailAddress),
        new XElement("MobileNumber", c.MobileNumber),
        new XElement("MobileCarrier", c.sMobileCarrier)
        )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM