سؤال

أنا أصلا سألت هذا السؤال على RefactorMyCode, ولكن لا ردود هناك...

أساسا أنا مجرد محاولة تحميل 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
هل كانت مفيدة؟

المحلول

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

السطر الأول هنا زائدة - يتم إنشاء مثيل XmlDocument ، ثم إعادة تعيين متغير:

Dim returnXDoc As XmlDocument = xDoc.Clone()

هذا يفعل نفس الشيء.

كما ترى يبدو أن إدراج كل XmlNode من عقدة قائمة في مكان مختلف في XmlDocument ثم لا أستطيع أن أرى كيف يمكن ان تفعل ذلك بأي طريقة أخرى.

قد يكون هناك أسرع XPath التعبيرات يمكن أن تكتب على سبيل المثال قبل انتظار تعبير XPath مع "//" هو دائما تقريبا أبطأ طريقة للقيام بشيء ما ، خاصة إذا XML هو منظم بشكل جيد.أنت لم تظهر XML لذلك لم أستطع التعليق على هذا ولكن.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top