写程序需要换XML的根,感觉很不便,于是写了一个函数,大致思路及实现如下:
首先觉得利用XSLT还能过滤一些东西,然后再发送回客户端,所以决定采用XSLT
然后就是尝试写一个换根的XSL,如下
<?xml version="1.0" encoding="gb2312" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="gb2312" omit-xml-declaration="yes" indent="yes" />
<xsl:template match="/">
<NEWNODENAME>
<xsl:apply-templates select="@* | node()" />
</NEWNODENAME>
</xsl:template>
<xsl:template match="@* | node()">
<xsl:choose>
<xsl:when test=".!=ancestor::node()"><xsl:copy><xsl:apply-templates select="@* | node()"/></xsl:copy></xsl:when>
<xsl:otherwise><xsl:apply-templates select="@* | node()"/></xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
大致意思是,解析一个XML中的所有结点及属性,如果非根就直接拷贝,否则就查看是否存在子结点及属性。具体资料请参照MSXML的SDK文档。
然后写一个函数,使得NEWNODENAME可以指定:
这段代码为VB.Net中的实现,ASP中实现时需要注意对象附值需要用Set,还有返回值的问题
Public Function ChangeXmlRootNodeName(ByRef oXml As MSXML2.DOMDocument, ByVal name As String) As String
If oXml Is Nothing Then
Return ""
End If
Dim sXslt As String
sXslt = "<?xml version=""1.0"" encoding=""gb2312"" ?>" & vbCrLf
sXslt = sXslt & "<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">" & vbCrLf
sXslt = sXslt & "<xsl:output method=""xml"" version=""1.0"" encoding=""gb2312"" omit-xml-declaration=""yes"" indent=""yes"" />" & vbCrLf
sXslt = sXslt & vbCrLf
sXslt = sXslt & "<xsl:template match=""/"">" & vbCrLf
sXslt = sXslt & "<" & name & ">"" & vbCrLf"
sXslt = sXslt & " <xsl:apply-templates select=""@* | node()""/>" & vbCrLf
sXslt = sXslt & "</" & name & ">" & vbCrLf
sXslt = sXslt & "</xsl:template>" & vbCrLf
sXslt = sXslt & vbCrLf
sXslt = sXslt & "<xsl:template match=""@* | node()"">" & vbCrLf
sXslt = sXslt & " <xsl:choose>" & vbCrLf
sXslt = sXslt & " <xsl:when test="".!=ancestor::node()""><xsl:copy><xsl:apply-templates select=""@* | node()""/></xsl:copy></xsl:when>" & vbCrLf
sXslt = sXslt & " <xsl:otherwise><xsl:apply-templates select=""@* | node()""/></xsl:otherwise>" & vbCrLf
sXslt = sXslt & " </xsl:choose>"" & vbCrLf"
sXslt = sXslt & "</xsl:template>"" & vbCrLf"
sXslt = sXslt & vbCrLf
sXslt = sXslt & "</xsl:stylesheet>" & vbCrLf
Dim oXsl As New MSXML2.DOMDocument
oXsl.async = False
oXsl.resolveExternals = False
oXsl.loadXML(sXslt)
Dim sXml As String
sXml = oXml.transformNode(oXsl)
sXml = AddXmlHeader(sXml)
sXsl = Nothing
Return sXml
End Function
还有,当然你也可以实现生成那个XSL的XSL文件,这就要看你如何设计了。