ループせずに XmlNodeList を XmlDocument に読み込みますか?
-
08-06-2019 - |
質問
私が最初にこの質問をしたのは、 MyCodeのリファクタリング, 、しかしそこには応答がありませんでした...
基本的に、私はただロードしようとしているだけです 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 を示していないので、これについてはこれ以上コメントできません。
所属していません StackOverflow