C# 将XML转换为JsonString时对其进行排序

C# 将XML转换为JsonString时对其进行排序,c#,xml,sorting,json.net,C#,Xml,Sorting,Json.net,这是我未分类的XML示例 <hierarchy> <date>2015/02/27 16:37:10</date> <folder name="Root" id="Root"> <file id="Erstg_20.xlsx" /> <file id="AAERG_20.xlsx" /> <folder name="Xmdg" id="Xmdg">

这是我未分类的XML示例

<hierarchy>
<date>2015/02/27 16:37:10</date> 
   <folder name="Root" id="Root">
        <file id="Erstg_20.xlsx" /> 
        <file id="AAERG_20.xlsx" />
      <folder name="Xmdg" id="Xmdg">
        <file id="DatePicker_20.xlsx" /> 
        <file id="Abcd_20.xlsx" />
   </folder>
   <folder name="Axcd" id="Axcd">
        <file id="Zfcd_20.xlsx" />
        <file id="Abcd_20.xlsx" />
   </folder>
</folder>
</hierarchy>

例如,您需要将字典序列化为json


您可以使用Folders(必须对其进行编码)类作为键,以及文件列表(也必须对其进行编码)作为值。您可以轻松地对列表和字典进行排序(不要忘记将compareTo方法编码)。

如果XSLT是一个选项,您可能需要使用以下方法:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>

<!-- default : copy everything as is -->
<xsl:template match='node()  |  @*'>
    <xsl:copy>
        <xsl:apply-templates select="@*  |  node()"/>
    </xsl:copy>
</xsl:template>

<!-- for elements hierarchy and folder : -->
<!-- sort these before copying -->
<xsl:template match="hierarchy | folder">
    <xsl:copy>
        <xsl:for-each select="@*  |  *">
            <xsl:sort select="@id"/>
            <xsl:apply-templates select="."/>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

您需要对xml进行排序。非常难看,因为您的xml似乎是递归的(文件夹中的文件夹中可能有文件)。在单个文件夹中,文件和文件夹之间的顺序是什么?首先是所有文件(按id排序),首先是所有文件夹(按id排序),然后是文件和文件夹混合并按IDies排序。这是递归的。。根文件夹将始终具有相同的名称和ID,因此首先我想按其在根文件夹中的ID对文件进行排序,然后按文件夹中的文件夹和文件夹中的文件进行排序。是否有原因使用SerializeXmlNode而不是使用中间对象来存储反序列化的内容,使用LINQ对其排序,然后将此结构转换为Json?
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>

<!-- default : copy everything as is -->
<xsl:template match='node()  |  @*'>
    <xsl:copy>
        <xsl:apply-templates select="@*  |  node()"/>
    </xsl:copy>
</xsl:template>

<!-- for elements hierarchy and folder : -->
<!-- sort these before copying -->
<xsl:template match="hierarchy | folder">
    <xsl:copy>
        <xsl:for-each select="@*  |  *">
            <xsl:sort select="@id"/>
            <xsl:apply-templates select="."/>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>
        // load XML file
        XmlDocument doc = new XmlDocument();
        doc.Load(xmlFilePath);
        // load XSLT file
        var transformation = new XslCompiledTransform();
        transformation.Load(@"C:\Temp\SortAndCopy.xslt");
        // perform transformation with XMLWriter
        // writing to new XML document
        XmlDocument sortedXmlDoc = new XmlDocument();
        using (XmlWriter xw = sortedXmlDoc.CreateNavigator().AppendChild())
        {
          transformation.Transform(doc, null, xw);
          xw.Close();
        }
        // further process sortedXmlDoc ...