Carregar um XmlNodeList em um XmlDocument sem loop?
-
08-06-2019 - |
Pergunta
Eu originalmente fiz esta pergunta em Refatorar meu código, mas não obtive respostas lá ...
Basicamente, estou apenas tentando carregar um XmlNodeList
em um XmlDocument
e eu queria saber se existe um método mais eficiente do que o loop.
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
Solução
Dim returnXDoc As New XmlDocument(xDoc.NameTable)
returnXDoc = xDoc.Clone()
A primeira linha aqui é redundante - você está criando uma instância de um XmlDocument e reatribuindo a variável:
Dim returnXDoc As XmlDocument = xDoc.Clone()
Isso faz o mesmo.
Vendo que você parece estar inserindo cada XmlNode da sua lista de nós em um local diferente no novo XmlDocument, não vejo como você poderia fazer isso de outra maneira.
Pode haver expressões XPath mais rápidas que você poderia escrever, por exemplo, pré-pender uma expressão XPath com "//" é quase sempre a maneira mais lenta de fazer algo, especialmente se o seu XML estiver bem estruturado.Você não mostrou seu XML, então não pude comentar mais sobre isso.