2013-02-11 20 views
1

我附加到現有的xml文件:代碼如下:我使用C#.net 4.5 VS 2012並創建一個WPF應用程序。附加Xml給定次數

我怎麼可以追加這個說30倍,只改變D100屬性號碼爲2,3,4,5等? 其他值是相同的!

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Navigation; 
using System.Windows.Shapes; 
using System.Xml; 

namespace AppendX 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     private void Button_Click_1(object sender, RoutedEventArgs e) 
     { 
      XmlDocument doc = new XmlDocument(); 
      doc.Load("C:\\Temp.xml"); 

      XmlNamespaceManager namespaces = new XmlNamespaceManager(doc.NameTable); 
      namespaces.AddNamespace("flp", "http://www.w3.org/2001/flp"); 



      XmlNode nextNode = doc.SelectSingleNode("/flp:Tab/flp:Designs", namespaces); 

      XmlElement D100 = doc.CreateElement("flp", "D100", "http://www.w3.org/2001/flp"); 
      D100.SetAttribute("Number", "2"); 

      XmlElement Code = doc.CreateElement("flp", "Code", "http://www.w3.org/2001/flp"); 
      Code.InnerText = "B"; 
      D100.AppendChild(Code); 

      XmlElement Documented = doc.CreateElement("flp", "Documented", "http://www.w3.org/2001/flp"); 
      Documented.InnerText = "false"; 
      D100.AppendChild(Documented); 

      nextNode.AppendChild(D100); 

      doc.Save("test1.xml"); 



     } 
    } 
} 

這裏是我使用的示例xml,對不起,我打算把這個!

<flp:Tab xmlns:flp="http://www.w3.org/2001/flp" Title="Testing"> 
    <flp:Form Number="0" id="1005" /> 
    <flp:Rev Time="2013-01-21T15:08:00"> 
    <flp:Author Name="Brad" Aid="15" /> 
    </flp:Rev> 
    <flp:Designs Id="D100"> 
    <flp:D100 Number="1"> 
     <flp:Code>A</flp:Code> 
     <flp:Documented>true</flp:Documented> 
    </flp:D100> 
    </flp:Designs> 
</flp:Tab> 
+2

你*有*使用'XmlDocument'嗎? LINQ to XML最終代碼簡單得多。即使你*不得不使用'XmlDocument',你試過了循環的方式嗎?它看起來像你可能只是圍繞代碼開始'XmlElement D100 = ...',結束於'nextNode.AppendChild(D100);'...... – 2013-02-11 07:14:08

回答

1

創建一個單獨的私有函數,該函數將根據參數處理文檔元素的創建。例如:

private xmlelement dothework(string param1, string param2){ 

    'do all necessary work to set up the element in here and then return it 

} 

我會分離喜歡這個工作,創建工作的各個部分不同的功能,所以,最終你可以遍歷每個附加到文件。