The XML reader/writer is complete! This means that we will be able to load and save the users information. Here is some of the code:
public class XMLRead {
static double PSVolt, PSAmp = 0; // Variables for the power supply
static double MVolt, MAmp, MSpeed, MTorque, MDriveShaft = 0; // Variables for the motor
static double WiLen, WiOhm, WiArea, WiRes = 0; // Variables for the wire
static double WhDiam, WhMu = 0; // Variables for the wheel
static double RWeight = 0; // General variables for the robot
static String WiCircuit = " "; // Type of circuit
public static void write(String name) {
try{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
// Makes the root element robot
Document doc = documentBuilder.newDocument();
Element rootElement = doc.createElement("robot");
doc.appendChild(rootElement);
// The next blocks of code are all children to the root element "robot".
Element PSvoltage = doc.createElement("PSvoltage");
PSvoltage.appendChild(doc.createTextNode(Double.toString(PSVolt)));
rootElement.appendChild(PSvoltage);
// Creates an instance of TransformerFactory so that a "real" XML file can be created
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(name));
// Exports the XML
// To clarify: this is when the XML file is made on the local hard drive.
transformer.transform(source, result);
public static void read(String doc) throws IOException, SAXException, ParserConfigurationException{
File file = new File(doc);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
// Gets the info and makes it an double
PSVolt = Double.parseDouble(document.getElementsByTagName("PSvoltage").item(0).getTextContent());
public static void main (String args []) throws IOException, SAXException, ParserConfigurationException, DOMException, TransformerException {
try{
read("robot.xml");
}catch (FileNotFoundException e){
System.err.println("file not found");
}
try{
write("file.xml");
}catch (NullPointerException e){
e.printStackTrace();
}
System.out.println("done");
The complete code can be found in the drop box folder. In fact, the code is already in a folder that can be downloaded and imported into eclipse to work on.
No comments:
Post a Comment