I am using TypeScript to create a JavaScript function. The function will need to return an XML string which contains keys and values, the values coming from the function's parameters. I would like it to be done safely, for example Terms & Conditions
would need encoding to Terms & Conditions
. I have seen the DOMParser is recommended for processing XML.
My function currently looks like this:
createDocumentXml(base64Document: string, category: string, documentName: string, documentExtension: string, userId: number, documentSizeBytes: number): string {
let xmlTemplate =
'<document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +
'<active>true</active>' +
'<category></category>' +
'<content></content>' +
'<createdByID></createdByID>' +
'<createdDate xsi:nil="true"/>' +
'<description></description>' +
'<fileExtension></fileExtension>' +
'<name></name>' +
'<size></size>' +
'</document>'
// use a DOM parser to modify the XML safely (i.e. escape any reserved characters)
let parser = new DOMParser();
let xmlDocument = parser.parseFromString(xmlTemplate, 'text/xml');
xmlDocument.getElementsByTagName('category')[0].textContent = category;
xmlDocument.getElementsByTagName('content')[0].textContent = base64Document;
xmlDocument.getElementsByTagName('createdByID')[0].textContent = userId.toString();
xmlDocument.getElementsByTagName('description')[0].textContent = documentName;
xmlDocument.getElementsByTagName('fileExtension')[0].textContent = documentExtension;
xmlDocument.getElementsByTagName('name')[0].textContent = documentName;
xmlDocument.getElementsByTagName('size')[0].textContent = documentSizeBytes.toString();
let serializer = new XMLSerializer();
return serializer.serializeToString(xmlDocument);
}
When called, it returns a string such as this:
<document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<active>true</active>
<category>Correspondence\Emails</category>
<content>ZmlzaCAmIGNoaXBzIQ==</content>
<createdByID>6627774</createdByID>
<createdDate xsi:nil="true"/>
<description>Terms & Conditions</description>
<fileExtension>docx</fileExtension>
<name>Terms & Conditions</name>
<size>12345</size>
</document>
How can I get it to just return the inner XML elements without the document
root?
<active>true</active>
<category>Correspondence\Emails</category>
<content>ZmlzaCAmIGNoaXBzIQ==</content>
<createdByID>6627774</createdByID>
<createdDate xsi:nil="true"/>
<description>Terms & Conditions</description>
<fileExtension>docx</fileExtension>
<name>Terms & Conditions</name>
<size>12345</size>
I have tried omitting the root from my xmlTemplate
but the DOMParser.parseFromString
requires one.
The result from this function is stored and subsequently passed into another function which creates the full XML data (including a root node) by inserting it at the relevant place.