Java Reference
In-Depth Information
Handling Import XML Events
You can define the ImportXMLOperation() method in SketcherFrame like this:
// Handle Import XML menu item events
private void importXMLOperation() {
checkForSave();
// Now get the destination file path
Path file = showDialog(
"Open XML Sketch File",
// Dialog window title
"Open",
// Button label
"Read a sketch from an XML file",
// Button tooltip text
xmlFileFilter,
// File filter
null);
// No file selected
if(file != null) {
openXMLSketch(file);
}
}
Directory "Sketcher reading and writing XML"
Reading an XML file containing a sketch replaces the current sketch, so you call checkForSave() in
case the current sketch has not been saved. If the showDialog() method returns a non-null Path object, you
pass it to the openXMLFile() method that reads the sketch from the file at the specified path.
Reading the XML File
You read the XML file and create a Document object from it using a Transformer object.
// Read an XML sketch from a file
private void openXMLSketch(Path file) {
try (BufferedInputStream xmlIn =
new BufferedInputStream(Files.newInputStream(file))){
StreamSource source = new StreamSource(xmlIn);
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
builderFactory.setValidating(true);
DocumentBuilder builder = builderFactory.newDocumentBuilder();
builder.setErrorHandler(this);
Document xmlDoc = builder.newDocument();
DOMResult result = new DOMResult(xmlDoc);
// Create a factory object for XML transformers
Search WWH ::




Custom Search