将XmlNodeList加载到XmlDocument中而不循环?
时间:2020-03-05 18:39:59 来源:igfitidea点击:
我最初在RefactorMyCode上问了这个问题,但那里没有任何回应。
基本上,我只是尝试将XmlNodeList
加载到XmlDocument
中,我想知道是否有比循环更有效的方法。
Private Function GetPreviousMonthsXml(ByVal months As Integer, ByVal startDate As Date, ByVal xDoc As XmlDocument, ByVal path As String, ByVal nodeName As String) As XmlDocument '' build xpath string with list of months to return Dim xp As New StringBuilder("//") xp.Append(nodeName) xp.Append("[") For i As Integer = 0 To (months - 1) '' get year and month portion of date for datestring xp.Append("starts-with(@Id, '") xp.Append(startDate.AddMonths(-i).ToString("yyyy-MM")) If i < (months - 1) Then xp.Append("') or ") Else xp.Append("')]") End If Next '' *** This is the block that needs to be refactored *** '' import nodelist into an xmldocument Dim xnl As XmlNodeList = xDoc.SelectNodes(xp.ToString()) Dim returnXDoc As New XmlDocument(xDoc.NameTable) returnXDoc = xDoc.Clone() Dim nodeParents As XmlNodeList = returnXDoc.SelectNodes(path) For Each nodeParent As XmlNode In nodeParents For Each nodeToDelete As XmlNode In nodeParent.SelectNodes(nodeName) nodeParent.RemoveChild(nodeToDelete) Next Next For Each node As XmlNode In xnl Dim newNode As XmlNode = returnXDoc.ImportNode(node, True) returnXDoc.DocumentElement.SelectSingleNode("//" & node.ParentNode.Name & "[@Id='" & newNode.Attributes("Id").Value.Split("-")(0) & "']").AppendChild(newNode) Next '' *** end *** Return returnXDoc End Function
解决方案
回答
Dim returnXDoc As New XmlDocument(xDoc.NameTable) returnXDoc = xDoc.Clone()
第一行是多余的,我们可以创建XmlDocument的实例,然后重新分配变量:
Dim returnXDoc As XmlDocument = xDoc.Clone()
这样做也一样。
看来我们似乎将节点列表中的每个XmlNode插入新XmlDocument中的不同位置,然后我看不到我们怎么可能以其他方式进行此操作。
我们可能会编写更快的XPath表达式,例如,在XPath表达式前加上" //"几乎总是最慢的方法,尤其是在XML结构良好的情况下。我们尚未显示XML,所以我不能对此进一步发表评论。