将XmlNodeList加载到XmlDocument而不循环?

时间:2008-08-15 20:33:34

标签: xml vb.net xmldocument xmlnode xmlnodelist

我最初在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

1 个答案:

答案 0 :(得分:2)

Dim returnXDoc As New XmlDocument(xDoc.NameTable)
returnXDoc = xDoc.Clone()

这里的第一行是多余的 - 你正在创建一个XmlDocument的实例,然后重新分配变量:

Dim returnXDoc As XmlDocument = xDoc.Clone()

这也是一样。

看到你似乎将每个XmlNode从你的节点列表插入新XmlDocument中的不同位置,然后我看不出你怎么可能以任何其他方式这样做。

您可以编写更快的XPath表达式,例如,使用“//”预先挂起的XPath表达式几乎总是执行某些操作的最慢方式,尤其是在XML结构良好的情况下。你还没有展示你的XML,所以我无法对此进行更深入的评论。