1

I have the following XML:

<?xml version="1.0" encoding="utf-8"?>
<foo>
  <bar key="baz" value='
{
  "a": {
    "b": {
      "c": "info"
    }
  }
}
' />
</foo>

I want to load this file in ps, do some work with it then save it back. At the moment, what I do is the following:

$xmlDocument = [System.Xml.XmlDocument]::new()
$xmlDocument.PreserveWhitespace = $true
$xmlDocument.Load('.\my.xml')

$settings = [System.Xml.XmlWriterSettings]@{
    Encoding = [System.Text.UTF8Encoding]::new($true)
    Indent   = $true
}

$xmlWriter = [System.Xml.XmlWriter]::Create('.\my.xml', $settings)
try {
    $xmlDocument.Save($xmlWriter)
}
finally {
    $xmlWriter.Dispose()
}

And I get the following output.

<?xml version="1.0" encoding="utf-8"?>
<foo>
    <bar key="baz" value="&#xD;&#xA;{&#xD;&#xA;  &quot;a&quot;: {&#xD;&#xA;    &quot;b&quot;: {&#xD;&#xA;      &quot;c&quot;: &quot;info&quot;&#xD;&#xA;    }&#xD;&#xA;  }&#xD;&#xA;}&#xD;&#xA;" />
</foo>

Is it possible to write this file without escaping the values?

Vivere
  • 662
  • 2
  • 13
  • Are you trying to write JSON into XML element attribute value? If so, [what for](https://meta.stackexchange.com/a/66378)? – vonPryz Mar 26 '21 at 11:42
  • If you can modify the schema, I recommend storing the JSON as element text, so you can use a [CDATA](https://stackoverflow.com/q/2784183/7571258) section to prevent any escaping: `` – zett42 Mar 26 '21 at 11:47
  • @zett42 I can't really change it. – Vivere Mar 26 '21 at 12:40
  • @vonPryz I totally get it. Some colleagues made some bad decision when writing the Web.config in an asp.net project and now I have to find a way for these changes... – Vivere Mar 26 '21 at 12:41
  • Just an idea: Try to override `XmlWriter` methods that write attributes, e. g. `WriteAttributes`, `WriteAttributeString` – zett42 Mar 27 '21 at 19:16
  • I solved it in an unorthodox way. I did what I had to do to the XML file, and when I would encounter a JSON value, I would keep it in an array, and replace that value with a GUID. I would save the XML doc with the changes made, and after that, I would open the file raw, regex match the GUID and replace it with the JSON value. – Vivere Mar 29 '21 at 16:49

0 Answers0