【问题标题】:Automatically format a long outerXml string自动格式化一个长的 outerXml 字符串
【发布时间】:2015-09-29 09:17:06
【问题描述】:

我有多个大型 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>

【问题讨论】:

  • 所以你不能使用XmlTextWriter

标签: vb.net streamwriter xml-formatting outerxml


【解决方案1】:

使用 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

【讨论】:

    【解决方案2】:

    因此,对于任何可能遇到此问题并对我如何解决它感兴趣的人,这就是我使用的...

        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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多