假设我按以下方式设置了5个XML文档。
123.xml
<link xlink="ABC">ABC</link>
<link xlink="DEF">DEF</link>
<link xlink="GHI">GHI</link>
ABC.xml
<link xlink="JKL">JKL</link>
JKL.xml
<link xlink="ABC">ABC</link>
DEF.xml 和 GHI.xml 中没有链接标记。
在VB.NET中,如果我以123.xml开头递归调用这些文件并且我的方法调用如下所示,我将如何摆脱由JKL文件调用回复ABC文件引起的无限循环为了仍然得到递归中没有被调用的DEF和GHI文件?请记住,这只是一个示例,无限循环可能会导致大量XML文件中的任何位置,因此我不会总是知道123是我需要返回的文件才能仍然获得转义无限循环后的DEF和GHI文件。
Public Sub Get_Next_Link(filename as String)
Dim xDoc As New XmlDocument()
xDoc.Load(filename)
Dim xNodeList As XmlNodeList = xDoc.SelectNodes("//link")
For Each xNode as XMLNode in xNodeList
Get_Next_Link(get the xlink attribute and + ".xml" here)
Next
End Sub
答案 0 :(得分:3)
我不常使用VB.Net的Static
关键字:)
Public Sub Get_Next_Link(filename as String)
Static completed As new HashSet(Of String)()
Dim xDoc As New XmlDocument()
xDoc.Load(filename)
Dim xNodeList As XmlNodeList = xDoc.SelectNodes("//link")
For Each xNode as XMLNode in xNodeList
Dim nextFile As String = 'get the xlink attribute and + ".xml" here
If completed.Contains(nextFile) Then Continue
completed.Add(nextFile)
Get_Next_Link(nextFile)
Next
End Sub
您可能想要添加的一件事是在单独的递归运行中重置completed
变量的方法。我可能想通过委托/闭包来实现这个目标:
Public Sub ReadXmlFiles(startFilename As String)
Dim completed As New HashSet(Of String)()
Dim NextLink As Action(Of String) = _
Sub(fileName)
Dim xDoc As New XmlDocument()
xDoc.Load(filename)
Dim xNodeList As XmlNodeList = xDoc.SelectNodes("//link")
For Each xNode as XMLNode in xNodeList
Dim nextFile As String = 'get the xlink attribute and + ".xml" here
If completed.Contains(nextFile) Then Continue
completed.Add(nextFile)
NextLink(nextFile)
Next
End Sub
NextLink(startFileName)
End Sub
但是当你可以将NextLink()
方法作为私有方法放在同一个类中时,这可能是不必要的复杂。不需要花哨的lambda语法。仍然......你可以说这更清楚,因为它表明NextLink()仅存在于ReadXmlFiles()中,并且它在Stack Overflow中用于将所有内容保存到单个方法中。