Search code examples
xmltext

Transforming plain text into text an xml document can handle?


Is there a method to transform a string of text, into text I can place into an .xml document? Mainly, I just want to replace characters like " or < with their &quot; or &lt; equivalent.

___text.txt______
This is some "text" I'd like to put into an .xml document

...transformed so I can paste it into a document like this...

___theme.xml______
<desc>
    This is some &quot;text&quot; I'd like to put into an .xml document
</desc>

(Sorry to ask what has to be a very basic question, researching this or even just looking for tools or converters has proven frustratingly fruitless. Maybe I'm lacking the correct words for what I'm trying to do?)


Solution

  • Using a Powershell script which does not need any tools installed. XML does not need the quotes escaped.

    using assembly System.Xml.Linq 
    
    $Filename = 'c:\temp\test.xml'
    $text = 'This is some "text" I''d like to put into an .xml document'
    
    $root = '<desc></desc>'
    $xDoc = [System.Xml.Linq.XDocument]::Parse($root)
    
    $desc = $xDoc.Root;
    $desc.SetValue($text)
    
    $xDoc.Save($Filename)