Global Dictator
Global Dictator

Reputation: 1589

Using java to generating XML with specific DTD declarations

I need to generate a XML file that contains specific XML Declarations and DTD declarations as shown below:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE paymentService PUBLIC "-//CompanyName//DTD CompanyName PaymentService v2//EN"
"http://dtd.CompanyName.com/paymentService_v2.dtd">

The remaining XML to be generated also has a specific Elements and associated values.

I was wondering what would be the best way to generate this XML within my java class? Using String Buffer or DOM? Any suggestions with an example or sample code will be hugely appreciated.

Thanks

Upvotes: 1

Views: 4147

Answers (1)

Rudi Kershaw
Rudi Kershaw

Reputation: 12982

I would recommend using the Java DOM API. Dealing with XML or XHTML in String objects is notoriously time consuming and buggy, so try and use a propper parser like DOM whenever you have the option to.

The below code should add a doc type and your xml declaration using Java DOM. The <?xml... should be added to the top automatically when the DocumentBuilder creates your document.

    // Create document
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    //Create doc type
    DOMImplementation domImpl = doc.getImplementation();
    DocumentType doctype = domImpl.createDocumentType("paymentService", "-//CompanyName//DTD CompanyName PaymentService v2//EN", "http://dtd.CompanyName.com/paymentService_v2.dtd");
    doc.appendChild(doctype);
    // Add root element
    Element rootElement = doc.createElement("root");
    doc.appendChild(rootElement);

The XML created by the above should look like this;

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE paymentService PUBLIC "-//CompanyName//DTD CompanyName PaymentService v2//EN" "http://dtd.CompanyName.com/paymentService_v2.dtd"> 
<root>
</root>

A great many of the methods used in the code above can throw a large number and variety of exceptions, so make sure your exception handling is up to scratch. I hope this helps.

Upvotes: 1

Related Questions