2008-08-15 36 views
2

Je initialement posé cette question sur RefactorMyCode, mais nous avons eu aucune réponse là ...Charger un XmlNodeList dans un XmlDocument sans boucler?

Fondamentalement, je suis juste essayer de charger un XmlNodeList dans un XmlDocument et je me demandais s'il y a une méthode plus efficace que la boucle.

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 

Répondre

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

La première ligne ici est redondante - vous créez une instance d'un XmlDocument, réaffectant la variable:

Dim returnXDoc As XmlDocument = xDoc.Clone() 

Cela fait la même chose. Étant donné que vous semblez insérer chaque XmlNode de votre liste de nœuds à un emplacement différent dans le nouveau XmlDocument, je ne vois pas comment vous pourriez faire autrement. Il peut y avoir des expressions XPath plus rapides que vous pourriez écrire, par exemple une expression XPath pré-en attente avec "//" est presque toujours le moyen le plus lent de faire quelque chose, surtout si votre XML est bien structuré. Vous n'avez pas montré votre XML, donc je ne pourrais pas vraiment commenter cela plus loin.