我有一个未格式化的 xml 字符串(没有空格),我想制作一个 VBScript 函数,该函数接受该字符串作为其参数并使用制表符和换行符格式化 XML
我在网上很好地看了看,并接近了这个 http://blogs.msdn.com/b/robert_mcmurray/archive/2012/07/06/creating-quot-pretty-quot-xml-using-xsl-and-vbscript.aspx
这不起作用,因为“MSXML2.DomDocument”对象不支持根据我的判断写入字符串。
我试图访问对象的各种属性(即“xml”、“text”和“xml.text”),但都无济于事。
简单来说我需要一串凌乱的xml输入,一串格式化的xml输出
最佳答案
所有功劳都归功于罗伯特·麦克默里;我只是将他的脚本改写成一个函数:
Option Explicit
' ****************************************
Function prettyXml(ByVal sDirty)
' ****************************************
' Put whitespace between tags. (Required for XSL transformation.)
' ****************************************
sDirty = Replace(sDirty, "><", ">" & vbCrLf & "<")
' ****************************************
' Create an XSL stylesheet for transformation.
' ****************************************
Dim objXSL : Set objXSL = WScript.CreateObject("Msxml2.DOMDocument")
objXSL.loadXML "<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">" & _
"<xsl:output method=""xml"" indent=""yes""/>" & _
"<xsl:template match=""/"">" & _
"<xsl:copy-of select="".""/>" & _
"</xsl:template>" & _
"</xsl:stylesheet>"
' ****************************************
' Transform the XML.
' ****************************************
Dim objXML : Set objXML = WScript.CreateObject("Msxml2.DOMDocument")
objXML.loadXml sDirty
objXML.transformNode objXSL
prettyXml = objXML.xml
End Function
Dim sTest : sTest = "<a><b><c/></b></a>"
WScript.Echo sTest
WScript.Echo "----------"
WScript.Echo prettyXml(sTest)
WScript.Quit 0
输出:
cscript robmcm-2.vbs
<a><b><c/></b></a>
----------
<a>
<b>
<c/>
</b>
</a>
第二个想法:
除非您研究过 this ,否则不应使用上述内容。
关于xml - 在 VBScript 中格式化 XML 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25067839/