2016-05-21 67 views
0

我環顧了互聯網,但我找不到解決方案,儘管我猜這應該很簡單。將屬性和字符串添加到C#中的XML文件#

我有一個XML文檔。有看起來像兩個節點:

<Attachments> 
    </Attachments> 

<Templates> 
    </Templates> 

添加兩個元素到每個節點後,他們應該像:

<Attachments> 
     <Attachment INDEX0="Test1" /> 
     <Attachment INDEX1="Test2" /> 
     </Attachments> 

    <Templates> 
     <Template INDEX0="Test1">EMPTY</Template> 
     <Template INDEX0="Test2">EMPTY</Template> 
     </Templates> 

我嘗試的第一個下面的代碼:

XmlDocument doc = new XmlDocument(); 
     doc.Load(Path.Combine(Directory.GetCurrentDirectory(), "test.xml")); 
     XmlElement root = doc.DocumentElement; 
     XmlNode node = root.SelectSingleNode("//Attachments"); 

    List<String> list = new List<string>() {"Test1","Test2"}; 

    foreach(var item in list) 
    { 
     XmlElement elem = doc.CreateElement("Attachment"); 
     root.AppendChild(elem); 
     XmlNode subNode = root.SelectSingleNode("Attachment"); 
     XmlAttribute xKey = doc.CreateAttribute(string.Format("INDEX{0}", list.IndexOf(item).ToString())); 
     xKey.Value = item; 
     subNode.Attributes.Append(xKey); 
    } 

但這絕對沒有。我怎樣才能實現這兩種情況?

謝謝!

回答

1

我建議使用LINQ to XML,除非你有特定的原因,你不能。老XmlDocument API是相當痛苦的一起工作:

var items = new List<string> {"Test1", "Test2"}; 

var attachments = items.Select((value, index) => 
    new XElement("Attachment", new XAttribute("INDEX" + index, value))); 

var doc = XDocument.Load(@"path/to/file.xml"); 

doc.Descendants("Attachments") 
    .Single() 
    .Add(attachments); 

了工作演示見this fiddle

+0

太棒了!非常感謝你! – Canox

+0

一個問題。如何將內部文本放入其中。就像在模板節點中一樣? – Canox

+1

@Canox您現在最好的行動方式是查看一些關於LINQ to XML的文檔和教程。要將文本添加到元素,只需在構造函數參數中包含一些文本即可。要設置現有元素或屬性的文本,請設置其「Value」屬性。 –

0

對不起,我發現了錯誤。 foreach循環應該是這樣的:

 foreach(var item in list) 
     { 
      XmlElement elem = doc.CreateElement(string.Format("Attachment{0}", list.IndexOf(item))); 
      node.AppendChild(elem); 
      XmlNode subNode = root.SelectSingleNode(string.Format("//Attachment{0}", list.IndexOf(item))); 
      XmlAttribute xKey = doc.CreateAttribute(string.Format("INDEX{0}", list.IndexOf(item).ToString())); 
      xKey.Value = item; 
      subNode.Attributes.Append(xKey); 
     } 

,但我仍然不知道如何實現,在我的例子中,模板屬性的情況下。

相關問題