Re: MSXML : Create a document with a doctype declaration ?

Ron Bourret (rbourret@dvs1.informatik.tu-darmstadt.de)
Tue, 28 Apr 1998 15:44:27 +0200


> How to create a new XML document with a doctype declaration with msxml =
?
>=20
> Something like :
>=20
> <!DOCTYPE foo SYSTEM "http://foo.domain.xx">
> <foo>
> ...
> </foo>

Try the following, which creates a new Document object, adds elements, =
and saves it. =20
You might need to change the document encoding for it to work on your =
machine. The=20
output file is:

<?xml version=3D"1.0">
<!DOCTYPE foo SYSTEM "http://foo.domain.xx">
<foo>
<bar>foobar</bar>
</foo>

import com.ms.xml.om.Document;
import com.ms.xml.om.Element;
import com.ms.xml.util.XMLOutputStream;
import com.ms.xml.util.Name;

import java.io.FileOutputStream;

public class CreateFooBar
{
static public void main(String argv[])
{
try
{
Document d =3D createMSXMLDoc();
saveDoc(d);
}
catch (Exception e)
{
}
}
=20
static public Document createMSXMLDoc()
{
Document d =3D new Document();
Element xmlPINode, dtdNode, root, child, pcdata;

// Create the XML PI node.
xmlPINode =3D d.createElement(Element.PI, "xml");
d.addChild(xmlPINode, null);
d.setVersion("1.0");
=20
// Create the DOCTYPE node.
dtdNode =3D d.createElement(Element.DTD);
d.addChild(dtdNode, xmlPINode);
dtdNode.setAttribute(Name.create("NAME"), Name.create("foo"));
dtdNode.setAttribute(Name.create("URL"), =
Name.create("http://foo.domain.xx"));
=20
// Create the root element
root =3D d.createElement(Element.ELEMENT, "foo");
d.addChild(root, dtdNode);
=20
// Create a child element
child =3D d.createElement(root, Element.ELEMENT, =
Name.create("bar"), null);
=20
// Create PCDATA for the child element
pcdata =3D d.createElement(child, Element.PCDATA, null, "foobar");
=20
return (d);
}

static public void saveDoc(Document d) throws Exception
{
d.setEncoding("ASCII");
d.setOutputStyle(XMLOutputStream.PRETTY);
FileOutputStream file =3D new FileOutputStream("foobar.xml");
XMLOutputStream xmlFile =3D d.createOutputStream(file);
d.save(xmlFile);
}
}