0

I have multiple large XML files and am trying to extract 5 instances of a specific element and its children. I have the code all set, however, I HAVE to use StreamWriter to write out the xml. How can I do this so that it comes out properly indented, etc.

The string looks similar to this:

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

I want it to look like this:

<SampleMAIN>
    <Sample type="1">
        <Sample_Batch>123
    </Sample_Batch>
        <SampleMethod>1
    </SampleMethod>
</SampleMAIN>
Gmac
  • 169
  • 2
  • 14

2 Answers2

0

With using StreamWriter, the below code will output the format that you need and append to an existing xml file.

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
0

So for anyone who may come across this and was interested in how I resolved it, here is what I used...

    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()
Gmac
  • 169
  • 2
  • 14