Search code examples
xmlvbscript

vbs changes < to &lt; and my > to &gt; when importing file contents


I have absolutely no idea when it comes to VBScript so I was quite happy when I frankensteined two simple code snippets found online to insert the entire contents of a text file into an XML document.

All works well except my < have changed to &lt; and my > has changed to &gt;.

How can I overcome this?

My code:

Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("C:\test.txt", ForReading)

strText = objTextFile.ReadAll
objTextFile.Close

Set xmlDoc = CreateObject("Microsoft.XMLDOM")

xmlDoc.Async = "False"
xmlDoc.Load("C:\Audits.xml")

Set colNodes = xmlDoc.SelectNodes("/TOOLS")

For Each objNode In colNodes
   objNode.text = (strText)
Next

xmlDoc.Save "C:\Audits.xml"

Solution

  • A CDATA section allows < and >:

    CDATA sections allow developers to include the markup characters <, >, and & within element content without using character or entity references. Scripts, style sheets, program code, and sample XML code are frequently contained in CDATA sections.

    (Docs)

    Code:

      Dim oXML : Set oXML = CreateObject("Msxml2.DOMDocument")
      Set oXML.documentElement = oXML.createElement("a")
      Dim nd
      Set nd = oXML.createElement("b")
      nd.appendChild oXML.createTextNode("<>")
      oXML.documentElement.appendChild nd
      Set nd = oXML.createElement("c")
      nd.appendChild oXML.createCDATASection("<>")
      oXML.documentElement.appendChild nd
    

    Content of oXML.xml:

    <a><b>&lt;&gt;</b><c><![CDATA[<>]]></c></a>