[英]Automatically format a long outerXml string
我有多個大型XML文件,正在嘗試提取特定元素及其子元素的5個實例。 我已經設置了所有代碼,但是,我必須使用StreamWriter來寫出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>
使用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
因此,對於可能遇到此問題並對我的解決方案感興趣的任何人,這就是我所使用的...
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.