1

I'm trying to write an XML file using Matlab and I need to specify a DOCTYPE DTD at the header, but I haven't found any method for this in the Matlab documentation or questions related. Every question involving a DTD reference is about how to read an XML into Matlab.

What I am able to do now is an XML file of the type

<?xml version="1.0"?>
<root>
    <child>
        Hello world!
    </child>
</root>

with the code

docNode = com.mathworks.xml.XMLUtils.createDocument('root');
root = docNode.getDocumentElement;

child = docNode.createElement('child');
child.appendChild(docNode.createTextNode('Hello World!'));
root.appendChild(child);

xmlwrite(docNode)

However, I need the file to include a DTD reference:

<?xml version="1.0"?>
<!DOCTYPE root SYSTEM "root.dtd" []>
<root>
    <child>
        Hello world!
    </child>
</root>

Is there any function in com.mathworks.xml.XMLUtils for this? Or will I have to open the generated XML and manually insert the DTD reference?

1 Answer 1

0

You can stay with using the org.w3c.dom package: you can use the createDocumentType method of DOMImplementation.

domImpl = docNode.getImplementation();
doctype = domImpl.createDocumentType('root', 'SYSTEM', 'root.dtd');

With this update the full sample code is:

docNode = com.mathworks.xml.XMLUtils.createDocument('root');
domImpl = docNode.getImplementation();
doctype = domImpl.createDocumentType('root', 'SYSTEM', 'root.dtd');
docNode.appendChild(doctype);

root = docNode.getDocumentElement;

child = docNode.createElement('child');
child.appendChild(docNode.createTextNode('Hello World!'));
root.appendChild(child);

xmlwrite(docNode)

Output

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE root PUBLIC "SYSTEM" "root.dtd">
<root>
   <child>Hello World!</child>
</root>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.