将 XmlNodeList 加载到 XmlDocument 中而不循环?

Load an XmlNodeList into an XmlDocument without looping?

提问人:travis 提问时间:8/16/2008 最后编辑:jpalecektravis 更新时间:4/26/2012 访问量:11536

问:

我最初是在 RefactorMyCode 上问这个问题的,但在那里没有得到任何回应......

基本上我只是尝试将 an 加载到 an 中,我想知道是否有比循环更有效的方法。XmlNodeListXmlDocument

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
xml vb.net xmldocument xmlnode xmlnodelist

评论


答:

2赞 samjudson 8/19/2008 #1
Dim returnXDoc As New XmlDocument(xDoc.NameTable)
returnXDoc = xDoc.Clone()

此处的第一行是多余的 - 您正在创建 XmlDocument 的实例,然后重新分配变量:

Dim returnXDoc As XmlDocument = xDoc.Clone()

这做同样的事情。

看到您似乎将节点列表中的每个 XmlNode 插入到新 XmlDocument 中的不同位置,那么我看不出您如何以其他方式做到这一点。

您可以编写更快的 XPath 表达式,例如,在 XPath 表达式之前添加带有“//”的表达式几乎总是最慢的执行某些操作的方法,尤其是在 XML 结构良好的情况下。您还没有展示您的 XML,所以我无法对此发表进一步评论。