我正在处理一个txt文件,我想知道是否有办法强制流读取器在我使用当前读取的那个之后读取下一行。
我的代码:
Private Sub subTest()
Dim sr As New StreamReader("d:\input\cleanedUp.txt")
Dim doc As New XmlDocument
Dim root As XmlElement = doc.CreateElement("Views")
Dim ns As String = sr.ReadLine()
Dim nsAtt As XmlAttribute = doc.CreateAttribute("ClientCode")
nsAtt.Value = ns
root.Attributes.Append(nsAtt)
While Not sr.EndOfStream
Dim sLine As String = sr.ReadLine
doc.AppendChild(root)
Dim child As XmlElement = doc.CreateElement("View")
root.AppendChild(child)
Dim newAtt As XmlAttribute = doc.CreateAttribute("Name")
newAtt.Value = sLine
child.Attributes.Append(newAtt)
Dim subChild As XmlElement = doc.CreateElement("Criteria")
child.AppendChild(subChild)
subChild.InnerText = sLine
End While
sr.Close() : sr.Dispose()
Dim sett As New XmlWriterSettings
sett.Indent = True
Dim sw As XmlWriter = XmlWriter.Create("d:\input\data.xml", sett)
doc.Save(sw)
sw.Flush() : sw.Close()
End Sub
结果如下:
<?xml version="1.0" encoding="utf-8"?>
<Views ClientCode="WSMCABS">
<View Name="vACCESSONE">
<Criteria>vACCESSONE</Criteria>
</View>
<View Name="ACCESSONE">
<Criteria>ACCESSONE</Criteria>
</View>
</Views>
我想要的是:
<?xml version="1.0" encoding="utf-8"?>
<Views ClientCode="WSMCABS">
<View Name="vACCESSONE">
<Criteria>ACCESSONE</Criteria>
</View>
<View Name="vSample2">
<Criteria>SAMPLE2</Criteria>
</View>
</Views>
答案 0 :(得分:0)
您可以测试循环中是否有另一行可用并执行另一个ReadLine:
While Not sr.EndOfStream
Dim sLine As String = sr.ReadLine
DoSomethingWithLine(sLine)
If Not sr.EndOfStream Then
sLine = sr.ReadLine
DoSomethingElseWithLine(sLine)
End If
End While
答案 1 :(得分:0)
所以我遇到的问题几乎就是读者会为每一行读取创建一个新的子/子,而我想要一个有多个子项的孩子。所以它有点像黑客,但我能够通过设置一个适用于我的情况的某些条件的循环来实现这一点。对于尝试完成类似事情的其他人来说,这可能不是最好的答案,但它对我有用,因为我的文本文件是由以&#34; v&#34;开头的SQL视图组成的。然后是该特定视图的标准。当程序看到另一个视图(以&#34; v&#34;开头)被读取时,该程序就不会添加额外的子节点。
While Not sr.EndOfStream
doc.AppendChild(root)
Dim child As XmlElement = doc.CreateElement("View")
root.AppendChild(child)
Dim newAtt As XmlAttribute = doc.CreateAttribute("Name")
newAtt.Value = sLine
child.Attributes.Append(newAtt)
If sLine.StartsWith("v") Then
sLine = sr.ReadLine
While Not sLine.StartsWith("v")
Dim subChild As XmlElement = doc.CreateElement("Criteria")
child.AppendChild(subChild)
subChild.InnerText = sLine
sLine = sr.ReadLine
If sLine = Nothing Then
sLine = sr.ReadLine
End If
If sLine = Nothing Then
Exit While
End If
End While
End If
End While
sr.Close() : sr.Dispose()