MSXML : Create a document with a doctype declaration ?

Ron Bourret rbourret at dvs1.informatik.tu-darmstadt.de
Tue Apr 28 16:16:02 BST 1998


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

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

<?xml version="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 = createMSXMLDoc();
         saveDoc(d);
      }
      catch (Exception e)
      {
      }
   }
   
   static public Document createMSXMLDoc()
   {
      Document d = new Document();
      Element  xmlPINode, dtdNode, root, child, pcdata;

      // Create the XML PI node.
      xmlPINode = d.createElement(Element.PI, "xml");
      d.addChild(xmlPINode, null);
      d.setVersion("1.0");
      
      // Create the DOCTYPE node.
      dtdNode = 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"));
      
      // Create the root element
      root = d.createElement(Element.ELEMENT, "foo");
      d.addChild(root, dtdNode);
      
      // Create a child element
      child = d.createElement(root, Element.ELEMENT, Name.create("bar"), null);
      
      // Create PCDATA for the child element
      pcdata = d.createElement(child, Element.PCDATA, null, "foobar");
      
      return (d);
   }

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


xml-dev: A list for W3C XML Developers. To post, mailto:xml-dev at ic.ac.uk
Archived as: http://www.lists.ic.ac.uk/hypermail/xml-dev/
To (un)subscribe, mailto:majordomo at ic.ac.uk the following message;
(un)subscribe xml-dev
To subscribe to the digests, mailto:majordomo at ic.ac.uk the following message;
subscribe xml-dev-digest
List coordinator, Henry Rzepa (mailto:rzepa at ic.ac.uk)




More information about the Xml-dev mailing list