Skip to content

Instantly share code, notes, and snippets.

@honda0510
Created February 9, 2011 01:10
Show Gist options
  • Save honda0510/817682 to your computer and use it in GitHub Desktop.
Save honda0510/817682 to your computer and use it in GitHub Desktop.
【VBA】XML インデント
Function indent(ByVal xml As String) As String
Dim writer As MSXML2.MXXMLWriter
Dim reader As MSXML2.SAXXMLReader
Dim dom As MSXML2.DOMDocument
Dim n As MSXML2.IXMLDOMNode
Set writer = New MSXML2.MXXMLWriter
' xml宣言を書き込まない
writer.omitXMLDeclaration = True
' インデントする
writer.indent = True
Set reader = New MSXML2.SAXXMLReader
Set reader.contentHandler = writer
reader.Parse xml
' 元のxmlから、xml宣言候補を退避
Set dom = New MSXML2.DOMDocument
dom.loadXML xml
Set n = dom.childNodes(0)
' インデントされたxmlを読み込む
' 元のxmlにxml宣言があったとしても、除外されている
dom.loadXML writer.output
' 元のxmlにxml宣言があれば、インデントされたxmlに追加
If n.nodeName = "xml" And n.nodeType = NODE_PROCESSING_INSTRUCTION Then
dom.InsertBefore n, dom.childNodes(0)
End If
' インデントされたxmlを返す
indent = dom.xml
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment