xml - 在 VBScript 中格式化 XML 字符串

标签 xml vbscript

我有一个未格式化的 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/

相关文章:

java - 启动 Activity 不起作用

java - 简单的 XML 框架解析器问题 - Android 中的 XML 解析

powershell - Windows 产品 key - 来自不同技术的不同答案

xml - 将 XmlNode 文本转换为整数

javascript - 无法获取XML中的节点值,如何获取?

python - 获取当前记录id

asp-classic - 经典 ASP : split by two patterns

c# - 使用 Excel 作为日志阅读器。如果 Excel 打开,如何写入日志文件?

java - java中使用JDOM解析XML(getChildren方法不返回List)

excel - 如何使用 VBScript 找出共享 Excel 文件的实例数