要描述 XML 文档结构,我们需要有模式定义文件。我们使用 profile.xsd 来构建那些允许我们根据模式定义文件列集、散集和验证 XML 文档实例的类。我们示例中的模式定义文件是 profile.xsd。
列集和散集 — 文件系统
现在我们来查看将 Java 实例列集到文件系统中的代码:
public void saveRecord(Record rec) {
try {
//Create a JAXBContext instance
JAXBContext jc = JAXBContext.newInstance(
"jaxbderived.profile"
);
String filename = null;
if ( !dirPath.endsWith(".xml"))
filename = dirPath + "/" + currentRecord.getCustomerID() +".xml";
else filename = dirPath;
textArea.append(" Saving file " + filename + "\n");
File f = new File(filename);
f.delete();
//Create a marshaler object
Marshaller m = jc.createMarshaller();
StringWriter swriter = new StringWriter();
//Marshal the record object
m.marshal(rec, swriter);
//Store the marshaled object in the String
String s = swriter.toString();
//Output this String to a file
FileOutputStream fout = new FileOutputStream(filename);
PrintWriter pw = new PrintWriter(fout);
pw.write(s);
//Flush and close file and printWriter
pw.flush();
if (pw != null) {
pw.close();
}
if (fout != null) {
fout.close();
}
textArea.append("Record saved...\n");
} catch (Exception e) {
e.printStackTrace();
}
}
以下是将文档实例从文件系统散集的代码:
public void loadSingleRecord() {
textArea.append("This may take some time.Please wait...\n");
try {
//Create a JAXBContext instance
JAXBContext jc = JAXBContext.newInstance(
"jaxbderived.profile"
);
//Create an unmarshaller instance
Unmarshaller u = jc.createUnmarshaller();
u.setValidating(true);
textArea.append("\nReading file " + dirPath + "\n");
//Unmarshal the Record object from FileInputStream
Record rec = (Record) u.unmarshal(fileToURL(dirPath));
//Store the object in the list
list.add(rec);
textArea.append("One record loaded.\n Size of the list is " +
list.size() + " \n"
);
} catch (Exception ex) {
textArea.append("There was an error while parsing \n" + dirPath +
"\nThis file will be ignored.\n"
);
textArea.append(
"Please note that this error is thrown when the source XML does not "
);
textArea.append(
"confirm to the Profile Record \nSchema definition.The error is given below \n"
);
textArea.append(ex.toString() +"\n\n");
} finally {
}
}
列集和散集 — 数据库
以下是将记录列集并保存到数据库中的代码:
public void saveRecord(Record rec) {
Statement st = null;
JAXBContext jc = null;
Marshaller m = null;
OraclePreparedStatement stmt = null;
try {
st = con.createStatement();
textArea.append("Saving record with customer id " +
rec.getCustomerID() + " \n"
);
//Delete previous record if any
st.execute(
"DELETE profile_tab pt WHERE pt.c1.extract('//Record/@CustomerID').getStringVal() ='" +
rec.getCustomerID() + "'"
);
if (st != null) {
st.close();
}
//Insert updated record
stmt = (OraclePreparedStatement) con.prepareStatement(
"INSERT INTO profile_tab VALUES (XMLType.CreateXML(?).CreateSchemaBasedXML('http://jaxbderived.profile/profile.xsd'))"
);
//Create JAXBContext instance
jc = JAXBContext.newInstance("jaxbderived.profile");
//Create Marshaller instance
m = jc.createMarshaller();
StringWriter swriter = new StringWriter();
//Marshal record object to a StringWriter
m.marshal(rec, swriter);
//Set the parameter
stmt.setString(1, swriter.toString());
//Execute the insert statement
stmt.execute();
con.commit();
textArea.append("One record has been added / updated \n");
} catch (Exception e) {
textArea.append(
"There was problem while adding / updating profile record in the database\n"
);
textArea.append("Error message is \n");
textArea.append(e.toString() + "\n");
} finally {
try {
if (st != null) {
st.close();
}
} catch (Exception e1) {
}
}
}
以下是将文档实例从数据库散集的代码:
private void createListFromDatabase() {
// Create a list instance
list = Collections.synchronizedList(new ArrayList());
Statement st = null;
ResultSet rs = null;
Unmarshaller u = null;
JAXBContext jc = null;
try {
//Create a JAXBContext instance
jc = JAXBContext.newInstance("jaxbderived.profile");
//Create unmarshaller object
u = jc.createUnmarshaller();
u.setValidating(false);
textArea.append("Reading records from the database \n");
st = con.createStatement();
//Select all records from profile_tab
rs = st.executeQuery(
"SELECT pt.c1.getStringVal() FROM profile_tab pt"
);
int i = 0;
while (rs.next()) {
//Retrieve the XMLType object as a String
String s = rs.getString(1);
//Get byte array from the String object
byte[] bytes = s.getBytes();
//Create ByteArrayInputStream object
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
try {
//Unmarshal the record
Record rec = (Record) u.unmarshal(new StreamSource(bais));
//Add the record to the list
list.add(rec);
} catch (Exception e1) {
textArea.append("There was an error while parsing " + i +
" th record from the result set \n" +
" This record has been skipped"
);
}
i++;
}
textArea.append("Number of records retrieved from the database : " +
list.size() + "\n"
);
listiterator = list.listIterator(0);
try {
listiterator.next();
} catch (Exception ex) {
}
if (st != null) {
st.close();
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (st != null) {
st.close();
}
} catch (Exception ex1) {
}
}
}