2015-07-10 66 views
0

我有多個大型的XML文件,並試圖提取特定元素及其子元素的5個實例。我有代碼全部設置,但是,我必須使用StreamWriter寫出XML。我怎樣才能做到這一點,以便它出來進行適當的縮進等自動格式化一個長的外部xml字符串

字符串類似於這樣:

<SampleMAIN><Sample type="1"><Sample_Batch>123 
</Sample_Batch><SampleMethod> 
</SampleMethod> 
</Sample></SampleMAIN> 

我希望它看起來像這樣:

<SampleMAIN> 
    <Sample type="1"> 
     <Sample_Batch>123 
    </Sample_Batch> 
     <SampleMethod>1 
    </SampleMethod> 
</SampleMAIN> 
+1

所以你不能用'XmlTextWriter'? – sstan

回答

0

因此,對於任何人誰可能會遇到這一點,很感興趣,我該怎麼解決呢,下面是我用什麼...

Dim dir As New DirectoryInfo("D:\data") 
    Dim sw As New StreamWriter("C:\Documents\largeFile.xml") 
    Dim xd As New XmlDocument 
    Dim iCount As Integer 

    sw.WriteLine("<?xml version=""1.0"" encoding=""ISO-8859-1""?>" & vbCrLf & "<Root>") 

    For Each fi As FileInfo In dir.GetFiles() 
     xd.Load(fi.FullName) 
     iCount = 0 

     For Each xn As XmlNode In xd.SelectNodes("//Root")   
      For Each xe As XmlElement In xn.ChildNodes 
       iCount += 1 
       sw.WriteLine(xe.OuterXml.ToString) 
       If iCount = 5 Then Exit For 
      Next 
      Exit For 
     Next 

    Next 

    sw.WriteLine("</Root>") 

    sw.Flush() : sw.Close() : sw.Dispose() 
0

對於使用StreamWriter,下面的代碼將輸出您需要的格式並附加到現有的xml文件。

Private Sub Button1_Click(sender As System.Object, _ 
          e As System.EventArgs) Handles Button1.Click 

    Dim sw As System.IO.StreamWriter 

    Dim St As String = "1" 
    Dim Sb As String = "123" 
    Dim Sm As String = "1" 

    sw = File.AppendText("C:\XML_Files\sampler_02.xml") 
    sw.WriteLine("<SampleMAIN>") 
    sw.WriteLine(" <Sample type=" & """" & St & """" & ">") 
    sw.WriteLine("  <Sample_Batch>" & Sb) 
    sw.WriteLine(" </Sample_Batch>") 
    sw.WriteLine("  <SampleMethod>" & Sm) 
    sw.WriteLine(" </SampleMethod>") 
    sw.WriteLine("</SampleMAIN>") 
    sw.Close() 

End Sub