使用C#对XML节点重新排序

时间:2019-02-20 15:04:39

标签: c# xml linq linq-to-xml

我的程序有一个列表框,允许用户选择“ CaseName”节点的顺序。列表框按显示顺序包含以下项目,

something

以下XML文件对应于上面的列表:

"Normal Cold Start"
"Normal Warm Start"
"Normal Very Hot Start"

我想更改XML文件以反映以下新顺序:

<?xml version="1.0" standalone="yes"?>
<DsCyclicLoading xmlns="http://tempuri.org/DsCyclicLoading.xsd">
  <CyclicLoading>
    <ComponentID>1</ComponentID>
    <ComponentName>ABC</ComponentName>
    <Standard>123</Standard>
    <CaseName>Normal Cold Start</CaseName>
  </CyclicLoading>
  <CyclicLoading>
    <ComponentID>2</ComponentID>
    <ComponentName>DEF</ComponentName>
    <Standard>456</Standard>
    <CaseName>Normal Warm Start</CaseName>
  </CyclicLoading>
  <CyclicLoading>
    <ComponentID>3</ComponentID>
    <ComponentName>GHI</ComponentName>
    <Standard>789</Standard>
    <CaseName>Normal Very Hot Start</CaseName>
  </CyclicLoading>
</DsCyclicLoading>

因此,新的XML文件如下所示:

"Normal Very Hot Start"
"Normal Cold Start"
"Normal Warm Start"

我该怎么做?

1 个答案:

答案 0 :(得分:0)

尝试一下:

NOT VALID

这给出了:

var xd = XDocument.Parse(@"<?xml version=""1.0"" standalone=""yes""?>
<DsCyclicLoading xmlns=""http://tempuri.org/DsCyclicLoading.xsd"">
    <CyclicLoading>
        <ComponentID>1</ComponentID>
        <ComponentName>ABC</ComponentName>
        <Standard>123</Standard>
        <CaseName>Normal Cold Start</CaseName>
    </CyclicLoading>
    <CyclicLoading>
        <ComponentID>2</ComponentID>
        <ComponentName>DEF</ComponentName>
        <Standard>456</Standard>
        <CaseName>Normal Warm Start</CaseName>
    </CyclicLoading>
    <CyclicLoading>
        <ComponentID>3</ComponentID>
        <ComponentName>GHI</ComponentName>
        <Standard>789</Standard>
        <CaseName>Normal Very Hot Start</CaseName>
    </CyclicLoading>
</DsCyclicLoading>");

var predefined = new[]
{
    "Normal Very Hot Start",
    "Normal Cold Start",
    "Normal Warm Start",
}
    .Select((x, n) => new { x, n })
    .ToDictionary(x => x.x, x => x.n);

var ns = XNamespace.Get("http://tempuri.org/DsCyclicLoading.xsd");

var nodes = xd.Root.Elements().OrderBy(x => predefined[x.Element(ns + "CaseName").Value]).ToArray();

xd.Root.ReplaceNodes(nodes);