基于子节点排序整个xdocument

von*_*dip 5 c# xml xslt xpath linq-to-xml

我有一个以下格式的xml:

<?xml version="1.0" encoding="utf-8"?>
<contactGrp name="People">
  <contactGrp name="Developers">
    <customer name="Mike" ></customer>
    <customer name="Brad" ></customer>
    <customer name="Smith" ></customer>
  </contactGrp>
  <contactGrp name="QA">
    <customer name="John" ></customer>
    <customer name="abi" ></customer>
  </contactGrp>
</contactGrp>
Run Code Online (Sandbox Code Playgroud)

我想根据客户名称对客户列表进行排序,并按以下格式返回文档:

<?xml version="1.0" encoding="utf-8"?>
<contactGrp name="People">
  <contactGrp name="Developers">
    <customer name="Brad" ></customer>
    <customer name="Mike" ></customer>
    <customer name="Smith" ></customer>
  </contactGrp>
  <contactGrp name="QA">
    <customer name="abi" ></customer>
    <customer name="John" ></customer>
  </contactGrp>
</contactGrp>
Run Code Online (Sandbox Code Playgroud)

我正在使用c#和当前的xmldocument.

谢谢

Jon*_*ton 2

如果您想要一个样式表并使用它来转换文档,那么:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
    <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/contactGrp">
    <contactGrp name="Developers">
      <xsl:apply-templates select="contactGrp"/>
    </contactGrp>
  </xsl:template>

  <xsl:template match="contactGrp/contactGrp">
    <contactGrp>
      <xsl:attribute name="name">
        <xsl:value-of select="@name"/>
      </xsl:attribute>

      <xsl:for-each select="customer">
        <xsl:sort select="@name"/>
        <xsl:copy-of select="."/>
      </xsl:for-each>

    </contactGrp>
  </xsl:template>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)