如何在c#中的Xelement中使用foreach循环

时间:2015-07-10 04:38:08

标签: c# xml xelement

 XElement doc = null;
 doc = new XElement("root");
 foreach (var content in emailContents)
                                    {
    doc.Add(new XElement("Email",
            new XElement("FromAddress", content.FromAddress),
            new XElement("EmailReceivedOn", content.receivedOnemail),
            new XElement("Subject", content.subject),
            new XElement("Body", content.body)));
    // I want to add the below code after the body element is created in the xml inside the email element section; How to do the same?
     foreach (var attachment in content.attachments)
        {
          doc.Add(new XElement("attachmentname"), attachment.Filename),
          doc.Add(new XElement(("attachmentpath"), attachment.Filepath)        
        }
}

基本上content.attachment是一个附件名列表,我想在body元素之后添加列表。怎么做?

2 个答案:

答案 0 :(得分:3)

一次性完成它很容易:

var doc =
    new XElement("root",
        new XElement("Email",
            new XElement("FromAddress", content.FromAddress),
            new XElement("EmailReceivedOn", content.receivedOnemail),
            new XElement("Subject", content.subject),
            new XElement("Body", content.body),
            content.attachments.Select(attachment =>
                new XElement("attachment",
                    new XElement("attachmentname", attachment.Filename),
                    new XElement("attachmentpath", attachment.Filepath)))));

我从这个示例数据开始:

var content = new
{
    FromAddress = "FromAddress",
    receivedOnemail = "receivedOnemail",
    subject = "subject",
    body = "body",
    attachments = new []
    {
        new
        {
            Filename = "Filename",
            Filepath = "Filepath",
        },
    },
};

我得到了这个XML:

<root>
  <Email>
    <FromAddress>FromAddress</FromAddress>
    <EmailReceivedOn>receivedOnemail</EmailReceivedOn>
    <Subject>subject</Subject>
    <Body>body</Body>
    <attachment>
      <attachmentname>Filename</attachmentname>
      <attachmentpath>Filepath</attachmentpath>
    </attachment>
  </Email>
</root>

答案 1 :(得分:1)

您正在向根元素添加附件,而不是添加电子邮件元素。你可以这样做。

XElement doc = null;
doc = new XElement("root");
doc.Add(new XElement("Email",
        new XElement("FromAddress", content.FromAddress),
        new XElement("EmailReceivedOn", content.receivedOnemail),
        new XElement("Subject", content.subject),
        new XElement("Body", content.body)));
 var email=doc.Element("Email"); // get email element from root Element
 foreach (var attachment in content.attachments)
    {
      //Add attachemnt information to email element.
      email.Add(new XElement("attachmentname"), attachment.Filename),
      email.Add(new XElement(("attachmentpath"), attachment.Filepath)        
    }