2008-08-15 47 views
2

我原來問過這個問題上RefactorMyCode,但沒有得到迴應有...加載一個XmlNodeList到一個XmlDocument沒有循環?

基本上我只是嘗試了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 

回答

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

這裏的第一行是多餘的 - 你正在創建一個XmlDocument的一個實例,然後重新分配變量:

Dim returnXDoc As XmlDocument = xDoc.Clone() 

這確實是相同的。

看來你似乎是從你的節點列表中插入每個XmlNode到新的XmlDocument中的不同位置,然後我看不出你怎麼可能以任何其他方式做到這一點。

您可以編寫更快的XPath表達式,例如預先等待帶有「//」的XPath表達式幾乎總是最慢的方式來執行某些操作,特別是如果您的XML結構良好。你還沒有顯示你的XML,所以我不能進一步評論這一點。

相關問題