3
$\begingroup$

When exporting an XMLObject (using Export/ExportString), is there any way to include a <!-- --> comment somewhere near the beginning of the file?

Note that it is not valid to put the comment as the very first line.

$\endgroup$
3
$\begingroup$

We can use the construction XMLObject["Comment"]["..."]. This is described in detail in this tutorial. For example...

ExportString[
  XMLElement["root", {}
  , { "\n"
    , XMLObject["Comment"][" hello "]
    , XMLElement["content", {}, {"content goes here"}]
    , "\n"
    }
  ]
, "XML"
]

... will generate this XML:

<root>
<!-- hello -->
<content>content goes here</content>
</root>

The documentation for XMLObject states that we can use this pattern to create various XML node types: declarations, comments, documents, doctypes, processing instructions and CDATA sections. Here is an example that shows each type:

ExportString[
  XMLObject["Document"][
    { XMLObject["Declaration"]["Version"->"1.0","Encoding"->"UTF-8","Standalone"->"no"]
    , XMLObject["Doctype"]["zot", "Public"->"-//???//zot", "System"->"urn://zot.zot"]
    }
  , XMLElement["zot", {}
    , { "\n"
      , XMLObject["Comment"][" witty remark "]
      , XMLElement["content", {}, {"to be determined"}]
      , "\n"
      , XMLObject["CDATASection"]["&&&!<><>!"]
      , "\n"
      , XMLObject["ProcessingInstruction"]["disposition: discard"]
      }
    ]
  , {}
  ]
, "XML"
]

yielding:

<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<!DOCTYPE zot PUBLIC '-//???//zot' 'urn://zot.zot'>
<zot>
<!-- witty remark -->
<content>to be determined</content>
<![CDATA[&&&!<><>!]]>
<?disposition: discard?>
</zot>
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.