Domanda

Inizialmente avevo posto questa domanda su RefactorMyCode, ma non ho ricevuto risposte...

Fondamentalmente sto solo provando a caricare un file XmlNodeList in un XmlDocument e mi chiedevo se esiste un metodo più efficiente del looping.

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
È stato utile?

Soluzione

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

La prima riga qui è ridondante: stai creando un'istanza di un XmlDocument, quindi riassegnando la variabile:

Dim returnXDoc As XmlDocument = xDoc.Clone()

Questo fa lo stesso.

Visto che sembra che tu stia inserendo ciascun XmlNode dal tuo elenco di nodi in una posizione diversa nel nuovo XmlDocument, non riesco a vedere come potresti farlo in un altro modo.

Potrebbero esserci espressioni XPath più veloci che potresti scrivere, ad esempio anteporre un'espressione XPath con "//" è quasi sempre il modo più lento per fare qualcosa, soprattutto se il tuo XML è ben strutturato.Non hai mostrato il tuo XML, quindi non potrei commentarlo ulteriormente.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top