Download NetBeans!

20070623 Saturday June 23, 2007

Integrating the XML Editor for Your File Type (Part 1)

Thanks to help from Vadiraj, I now know how to open non-XML files in the XML editor. Sometimes you have XML content in a file that does not end in ".xml". How do you let the IDE treat it like an XML file? Below, you see a file with the extension ".test" open in the XML editor. You know it is open there because of the syntax coloring and indentation, and because of the additional menu items that relate specifically to XML files:

How to do this:

  1. Use New File Type wizard, which will give you various classes. The only class we will need to change is the XxxDataObject.

  2. Add a dependency on XML Tools API.

  3. In the data object, change the extension class from MultiDataObject to XMLDataObject.

  4. Fill out the constructor with additional functionality by providing cookies for checking XML, validating XML, and transforming XML via XSLT, like this:

    public TestDataObject(FileObject pf, TestDataLoader loader) throws DataObjectExistsException, IOException {
    
        super(pf, loader);
    
        CookieSet cookies = getCookieSet();
        InputSource is = DataObjectAdapters.inputSource(this);
        Source source = DataObjectAdapters.source(this);
    
        cookies.add(new CheckXMLSupport(is));
        cookies.add(new ValidateXMLSupport(is));
        cookies.add(new TransformableSupport(source));
        cookies.add((Node.Cookie) DataEditorSupport.create(this, getPrimaryEntry(), cookies));
    
    }
  5. Make sure the import statements are correct:

    import java.io.IOException;
    import javax.xml.transform.Source;
    import org.netbeans.spi.xml.cookies.CheckXMLSupport;
    import org.netbeans.spi.xml.cookies.DataObjectAdapters;
    import org.netbeans.spi.xml.cookies.TransformableSupport;
    import org.netbeans.spi.xml.cookies.ValidateXMLSupport;
    import org.openide.filesystems.FileObject;
    import org.openide.loaders.DataObjectExistsException;
    import org.openide.loaders.XMLDataObject;
    import org.openide.nodes.CookieSet;
    import org.openide.nodes.Node;
    import org.openide.text.DataEditorSupport;
    import org.xml.sax.InputSource;

That's it. You're done. Your file will now be treated as an XML file, like all other XML files.

Jun 23 2007, 01:03:00 AM PDT Permalink