2012-12-24 86 views
0

我有以下格式追加XML節點到現有XML文件

<Attachment> 
<AttachmentName>Top Nav Menu.docx</AttachmentName> 
<Subject>Attachment1</Subject> 
<Sender>[email protected]</Sender> 
</Attachment> 

我想附帶其它附件,如附件後上述接近節點的XML。下面是我對寫作的XML文件編寫的代碼

var doc = new XDocument(

       new XDeclaration("1.0", "utf-16", "true"), 

       new XProcessingInstruction("test", "value"), 

       new XElement("Attachment",new XElement("AttachmentName", attachment.Name), 
              new XElement("Subject", exchangeEmailInformation.Subject), 
              new XElement("Sender", exchangeEmailInformation.Sender 
             ))); 
      doc.Save(ConfigInformation.BackUpPath + FolderId[index]+"\\Attachments"+index+".xml"); 
+0

附件是你的XML的根節點。你想要有幾個根元素? –

+0

沒有根元素。我需要添加一個新的附件,比如我在關閉附件節點後共享的xml格式 – JEMI

+1

LINQ到XML的'XDocument'是爲了操作XML規範定義爲格式良好的文檔。其中一個良構要求是包含所有其他元素的單根元素。因此,如果你想要有兩個頂層的'Attachment'元素節點,你想要構造的東西不是XML文檔,並且不能用'XDocument'來表示。你確定你想要嗎? –

回答

3

創建根節點您的附件:

var doc = new XDocument(
    new XDeclaration("1.0", "utf-16", "true"), 
    new XProcessingInstruction("test", "value"), 
    new XElement("Attachments", 
     new XElement("Attachment", 
      new XElement("AttachmentName", attachment.Name), 
      new XElement("Subject", exchangeEmailInformation.Subject), 
      new XElement("Sender", exchangeEmailInformation.Sender) 
    ))); 

當你決定要追加另一個附件,加載文檔,並添加附件根:

doc.Root.Add(new XElement("Attachment", 
    new XElement("AttachmentName", attachment.Name), 
    new XElement("Subject", exchangeEmailInformation.Subject), 
    new XElement("Sender", exchangeEmailInformation.Sender) 
)); 
0

我會使用XMLSerializer類。在那裏你可以像處理類一樣處理你的XML文件。隨便看看,你會喜歡它:)

加載XML - >在代碼使用類(修改,刪除,添加) - >序列化回XML

+0

給我鏈接 – JEMI

+0

http://www.jonasjohn.de/snippets/csharp/xmlserializer-example.htm –

相關問題