保留数据集行顺序 XmlWriter vb

Preserve Dataset row order XmlWriter vb

尝试编写一些代码以通过用户界面更改 XML 文件中的元素顺序。问题是:如何控制物理存储顺序元素写入 via WriteXML

比如我要改造:

<Image Name="Middle" file="Sauce.png" />
<Image Name="Top" file="Cheese.png" />
<Image Name="Bottom" file="PizzaBase.png" />

至:

<Image Name="Top" file="Cheese.png" />
<Image Name="Middle" file="Sauce.png" />
<Image Name="Bottom" file="PizzaBase.png" />

在文件中。到目前为止的方法:

.xml > 数据集 > datagridview(绑定 dataset.table)

这很好用,允许用户上下移动 row/element。当我在 Locals 中查看时,行的任何移动都会反映在 Dataset.table 中(即,如果 "Cheese" 移动到 DatagridView 的顶部,它也位于数据集中的顶部)。

但是,当我通过 XMLWriter 将其写回 XML 时,任何移动的行都会附加到 底部 xml,而不是数据集的相同顺序。例如,如果我向上移动 "Cheese",则输出为:

<Image Name="Middle" file="Sauce.png" />
<Image Name="Bottom" file="PizzaBase.png" />
<Image Name="Top" file="Cheese.png" />

四处搜索 - 在此找不到任何内容。有人有什么想法吗?


编辑:这就是我重新排序行的方式:

 Private Sub _RigRowUp_Click(sender As Object, e As EventArgs) Handles _RigRowUp.Click
        If IsNothing(_RigImgsDGV.DataSource)
            Return
        End If
        Dim selectedRow As DataRow = _RigXMLImgsDS.Tables("Image").Rows(_RigImgsDGV.CurrentRow.Index)
        Dim selectedindex As Integer = _RigXMLImgsDS.Tables("Image").Rows.IndexOf(selectedRow)
        If selectedindex <= 0 Then
            Return
        End If
        Dim newRow As DataRow = _RigXMLImgsDS.Tables("Image").NewRow()
        newRow.ItemArray = selectedRow.ItemArray
        _RigXMLImgsDS.Tables("Image").Rows.Remove(selectedRow)
        _RigXMLImgsDS.Tables("Image").Rows.InsertAt(newRow, selectedindex - 1)
        _RigImgsDGV.ClearSelection()
        _RigImgsDGV.CurrentCell = _RigImgsDGV.Rows(selectedindex - 1).Cells(0)
        _RigImgsDGV.Rows(selectedindex - 1).Selected = True
    End Sub

_RigXMLImgsDS 是数据集 RigImgsDGV 是 DataGridView

在其他地方的 public 子中绑定:

  _RigImgsDGV.DataSource = New BindingSource(_RigXMLImgsDS.Tables("Image"), Nothing)

终于想通了。您必须将数据集中更新的table写入临时table,然后清除数据集中的table,然后将临时table的行一一写入回到数据集中匹配的 table。代码(很抱歉直接从完整的脚本中提取出来,但应该说明过程):

Dim _tempDT As DataTable
    _tempDT = _RigXMLImgsDS.Tables("Image").Copy()
    _RigXMLImgsDS.Tables("Image").Clear()
    For Each DataRow In _tempDT.Rows
        _RigXMLImgsDS.Tables("Image").ImportRow(DataRow)
    Next

然后照常使用XMLWriter。感谢 Plutonix。