2017-06-15 44 views
0

我想要一個List<string>的原始XML數據的一部分追加到一個XML文件,如下所示:追加到特定位置的XML文件

XmlDocument doc = new XmlDocument(); 
XmlNode docnode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);   
doc.AppendChild(docnode); 

doc.AppendChild(doc.CreateProcessingInstruction("xml-stylesheet", "type='text/xsl' href=''")); 

XmlElement Ver = doc.CreateElement("Run"); 
Ver.SetAttribute("version", "3.0"); 
XmlElement elem = doc.CreateElement("List"); 
elem.SetAttribute("Name", ObjectName_string); 
doc.AppendChild(Ver); 
doc.DocumentElement.AppendChild(elem); 
doc.Save(@"1.xml"); 

List<string> data = Event_table.Rows.OfType<DataRow>().Select(dr=>dr.Field<string>(0)).ToList(); 


using (var writer = new StreamWriter(@"1.xml", append:true)) 
     { 


      writer.WriteLine("<cmList>"); 

      foreach (var row in data) 
      { 
       writer.WriteLine(row); 
      } 

      writer.WriteLine("</cmList>"); 
     } 

XML文件:這是最終的結果應該如何

<?xml version="1.0" encoding="UTF-8"?> 
<?xml-stylesheet type='text/xsl' href=''?> 
<Run version="3.0" startTime="3.0" endTime="3.0"> 
    <List Name="ABCD" /> 
    <cmList> 

     **// My Raw data should come here from List<string> data** 



    </cmList> 
</Run> 

我怎樣才能List<string> data追加原始XML數據中的元素<cmList>之間我試圖doeing一個write.BaseStream.Seek但給我一個錯誤:

Unable seek backward to overwrite data that previously existed in a file opened in Append mode.

回答

0

我寫了很多個月前的博客,專門討論如何從DataSet/DataTable獲取數據到XML(專門用於Excel)。看起來這可能對你有所幫助。只需排除告訴XML文件在Excel中打開的說明即可。它在VB.NET中,所以你將不得不使用類似的C#代碼。

DataSet to XML Blog

0

也許我不明白你的榜樣的東西,但你爲什麼不保存的xml文件來追加前的原始數據?

XmlDocument doc = new XmlDocument(); 
XmlNode docnode = doc.CreateXmlDeclaration("1.0", "UTF-8", null); 
doc.AppendChild(docnode); 
doc.AppendChild(doc.CreateProcessingInstruction("xml-stylesheet", "type='text/xsl' href=''")); 

XmlElement Ver = doc.CreateElement("Run"); 
Ver.SetAttribute("version", "3.0"); 
XmlElement elem = doc.CreateElement("List"); 
elem.SetAttribute("Name", ObjectName_string); 
XmlElement cmList = doc.CreateElement("cmList"); 

List<string> data = Event_table.Rows.OfType<DataRow>().Select(dr => dr.Field<string>(0)).ToList(); 
StringBuilder builder = new StringBuilder(); 
foreach (var row in data) 
{ 
    builder.AppendLine(row); 
} 
cmList.Value = builder.ToString(); 

elem.AppendChild(cmList); 
Ver.AppendChild(elem); 
doc.AppendChild(Ver); 
doc.Save(@"1.xml"); 
// do something with file 1.xml 
相關問題