Contributed by: Amit Kumar Saha
NetBeans 6.1 Beta comes with a DOM tree scanner which can generate Java classes for scanning the DOM tree of your XML file from the corresponding DTD file.
In this short tip, I will demonstrate to you the usage of DOM Tree Scanner
Say, you have (created or otherwise) a DTD file (for eg. mapping.dtd
<?xml version='1.0' encoding='UTF-8'?>
<!--
TODO define vocabulary identification
PUBLIC ID: -//vendor//vocabulary//EN
SYSTEM ID: http://server/path/mapping.dtd
--><!--
An example how to use this DTD from your XML document:
<?xml version="1.0"?>
<!DOCTYPE raidmap SYSTEM "mapping.dtd">
<raidmap>
...
</raidmap>
-->
<!--- Put your DTDDoc comment here. -->
<!ELEMENT raidmap (mddevice)*>
<!--- Put your DTDDoc comment here. -->
<!ELEMENT mddevice (mountpoint|device)*>
<!ATTLIST mddevice
name CDATA #IMPLIED
>
<!--- Put your DTDDoc comment here. -->
<!ELEMENT device EMPTY>
<!ATTLIST device
name CDATA #IMPLIED
>
<!--- Put your DTDDoc comment here. -->
<!ELEMENT mountpoint (#PCDATA)>).
Right-click on it and you will see a option "Generate DOM Tree Scanner" in the pop-up menu that appears. Click on it:
What you will have is a Java class which is all set to be used to scan through your XML file which conforms to your DTD. Its Magic!
In the Java class that is generated, you will see a method:
public void visitDocument() {
.
.
.
}
This will be your entry-point to the DOM scanner.
Just create another Java class:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package softwareraidtool;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/**
*
* @author amit
*/
public class MappingScannerDemo {
public static void main(String args[]) throws IOException, SAXException{
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Create the builder and parse the file
Document doc = factory.newDocumentBuilder().parse("mapping.xml"); //the file you want to parse and which conforms to the DTD
MappingScanner demo = new MappingScanner(doc);
demo.visitDocument();
}catch(ParserConfigurationException pc){
}
}
}
You will have to modify the DOM scanner class to fit your needs. In its original form, it will just parse the XML file.
Here are the files:
HTH, have fun!