2014-03-25 23 views
0

幫助我解決這個問題!我需要創建xml文件。我的XML文件的元素,我從文本文件(config screenos juniper)隔離。我想把關鍵詞作爲節點和元素。在xml表達式中使用循環foreach

我想實現這樣的輸出(XML文件):

<VR1> 

    <...> 

</VR1> 
<VR2> 

    <...> 

</VR2> 
<VR3> 

    <...> 

</VR3> 

但我只有這樣的輸出:

<VR3> 

     <...> 

    </VR3> 

這樣的代碼:

   foreach (var match in myCollection) 
      { 

       StringWriter stringwriter = new StringWriter(); 

       XmlTextWriter xmlTextWriter = new XmlTextWriter(stringwriter); 
       xmlTextWriter.Formatting = Formatting.Indented; 
       xmlTextWriter.WriteStartDocument(); 
       xmlTextWriter.WriteStartElement(match); 
       ; 
          ... 
          ... 

       xmlTextWriter.WriteEndElement(); 
       xmlTextWriter.WriteEndDocument(); 
       XmlDocument docSave = new XmlDocument(); 
       docSave.LoadXml(stringwriter.ToString()); 
       //write the path where you want to save the Xml file 
       docSave.Save(AppDomain.CurrentDomain.BaseDirectory.ToString() +"Roting.xml"); 
      } 

這裏MyCollection的包含:VR1,VR2,VR3。 似乎很明顯,我錯誤地使用循環foreach,但我不明白如何正確使用它在這種情況下。

+0

您正在覆蓋您的文檔 – RadioSpace

+0

同意!一切都變了 – user3214034

回答

1
  StringWriter stringwriter = new StringWriter(); 

      XmlTextWriter xmlTextWriter = new XmlTextWriter(stringwriter); 
      xmlTextWriter.Formatting = Formatting.Indented; 
      xmlTextWriter.WriteStartDocument();   

     foreach (var match in myCollection) 
     { 


      xmlTextWriter.WriteStartElement(match); 
      ; 
         ... 
         ... 

      xmlTextWriter.WriteEndElement(); 

     } 
      xmlTextWriter.WriteEndDocument(); 
      XmlDocument docSave = new XmlDocument(); 
      docSave.LoadXml(stringwriter.ToString()); 
      //write the path where you want to save the Xml file 
      docSave.Save(AppDomain.CurrentDomain.BaseDirectory.ToString() +"Roting.xml");