@Mifet 这是我用来创建 xml 文件的 java 文件:
package csheets.io;
import csheets.core.Cell;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import csheets.core.Spreadsheet;
import csheets.core.Workbook;
import csheets.ext.style.StylableCell;
import csheets.ext.style.StyleExtension;
import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.StringWriter;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
/**
* A codec for XML files.
*
* @author Cristiano
*/
public class XMLCodec implements Codec {
String xml;
private String keyWrite;
public XMLCodec() {
}
/*Metodo read, lê de um ficheiro XML, valida o ficheiro com o seu XSD
* correspondete e por fim preenche as celulas da spreadsheet com a
* informação contida no XML
* return Workbook;*/
public Workbook read(InputStream stream) throws IOException {
Workbook work = null;
try {
work = new Workbook();
int temp = 0;
Node nNode;
Element eElement = null;
StylableCell stylableCell;
/*Criação do documento*/
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setValidating(false);
dbFactory.setNamespaceAware(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(stream);
/*Validação do documento XML*/
Schema sch = carregarSchema("validate.xsd");
if (validarXml(sch, doc)) {
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("workbook");
nNode = nList.item(temp);
eElement = (Element) nNode;
nList = doc.getElementsByTagName("spreadsheet");
for (temp = 0; temp < nList.getLength(); temp++) {
nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
eElement = (Element) nNode;
String spreadTitle = eElement.getAttribute("title");
work.addSpreadsheet();
work.getSpreadsheet(temp).setTitle(spreadTitle);
NodeList nListCells = eElement.getElementsByTagName("cell");
int numCellsOnSpread = eElement.getElementsByTagName("cell").getLength();
for (int k = 0; k < numCellsOnSpread; k++) {
Node nNodeCell = nListCells.item(k);
Element eElementCell = (Element) nNodeCell;
String row = eElementCell.getAttribute("row");
String column = eElementCell.getAttribute("column");
String horizAlign = eElementCell.getAttribute("horizAlign");
String vertiAlign = eElementCell.getAttribute("vertiAlign");
String fontStyle = eElementCell.getAttribute("fontStyle");
String fontSize = eElementCell.getAttribute("fontSize");
String fontName = eElementCell.getAttribute("fontName");
String fgColor = eElementCell.getAttribute("fgColor");
String bgColor = eElementCell.getAttribute("bgColor");
String left = eElementCell.getAttribute("left");
String right = eElementCell.getAttribute("right");
String top = eElementCell.getAttribute("top");
String bottom = eElementCell.getAttribute("bottom");
String content = eElementCell.getAttribute("content");
int columnInt = Integer.parseInt(column);
int rowInt = Integer.parseInt(row);
stylableCell = (StylableCell) work.getSpreadsheet(temp).getCell(columnInt, rowInt).getExtension(StyleExtension.NAME);
stylableCell.setHorizontalAlignment(Integer.parseInt(horizAlign));
stylableCell.setVerticalAlignment(Integer.parseInt(vertiAlign));
Font font = new Font(fontName, Integer.parseInt(fontStyle), Integer.parseInt(fontSize));
stylableCell.setFont(font);
Color fgCol = new Color(Integer.parseInt(fgColor));
stylableCell.setForegroundColor(fgCol);
Color bgCol = new Color(Integer.parseInt(bgColor));
stylableCell.setBackgroundColor(bgCol);
Border cellBord = BorderFactory.createMatteBorder(Integer.parseInt(top), Integer.parseInt(left), Integer.parseInt(bottom), Integer.parseInt(right), Color.darkGray);
stylableCell.setBorder(cellBord);
stylableCell.setContent(content);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
work = new Workbook(3);
return work;
}
/*Metodo write, recebe um Workbook e OutputStream, cria um ficheiro XML com
* a informação contida nas celulas da spreadsheet*/
public void write(Workbook workbook, OutputStream stream) {
xml = null;
keyWrite = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String dataHora = dateFormat.format(date);
Writer writer = new StringWriter();
StreamResult strResult = new StreamResult(writer);
SAXTransformerFactory transFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
TransformerHandler transHandler = null;
try {
transHandler = transFactory.newTransformerHandler();
} catch (TransformerConfigurationException ex) {
ex.getMessage();
}
Transformer serializer = transHandler.getTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
transHandler.setResult(strResult);
try {
transHandler.startDocument();
} catch (SAXException ex) {
ex.getMessage();
}
AttributesImpl attributes = new AttributesImpl();
// <workbook>
try {
attributes.clear();
attributes.addAttribute("", "", "xmlns", "CDATA", "http://www.dei.isep.ipp.pt/lapr4");
attributes.addAttribute("", "", "xmlns:xsi", "CDATA", "http://www.w3.org/2001/XMLSchema-instance");
attributes.addAttribute("", "", "xsi:schemaLocation", "CDATA", "http://www.dei.isep.ipp.pt/lapr4 validate.xsd");
transHandler.startElement("", "", "workbook", attributes);
} catch (SAXException ex) {
ex.getMessage();
}
// <lastSave>
try {
attributes.clear();
transHandler.startElement("", "", "lastSave", attributes);
transHandler.characters(dataHora.toCharArray(), 0, dataHora.length());
transHandler.endElement("", "", "lastSave");
} catch (SAXException ex) {
ex.getMessage();
}
// <numSpreadsheets>
try {
attributes.clear();
transHandler.startElement("", "", "numSpreadsheets", attributes);
String numSheets = "" + workbook.getSpreadsheetCount();
transHandler.characters(numSheets.toCharArray(), 0, numSheets.length());
transHandler.endElement("", "", "numSpreadsheets");
} catch (SAXException ex) {
ex.getMessage();
}
Iterator<Spreadsheet> sheetsIterator = workbook.iterator(); //iterador paras as sheets
while (sheetsIterator.hasNext()) { //enquanto existirem sheets
Spreadsheet sheet = sheetsIterator.next(); //para cada sheet
// <spreadsheet>
try {
attributes.clear();
attributes.addAttribute("", "", "title", "CDATA", sheet.getTitle()); // <spreadsheet title="">
transHandler.startElement("", "", "spreadsheet", attributes);
} catch (SAXException ex) {
ex.getMessage();
}
Iterator<Cell> cellIterator = sheet.iterator(); //iterador para cells
while (cellIterator.hasNext()) { //enquanto houver cells
Cell cell = cellIterator.next(); //para cada cell
// <cell>
try {
if (!cell.getContent().equals("")) { //se não vazia
StylableCell stylableCell = (StylableCell) cell.getExtension(StyleExtension.NAME);
attributes.clear();
String horizAlign = "" + stylableCell.getHorizontalAlignment(); // alinhamento horizontal
attributes.addAttribute("", "", "horizAlign", "CDATA", horizAlign);
String vertiAlign = "" + stylableCell.getVerticalAlignment(); // alinhamento vertical
attributes.addAttribute("", "", "vertiAlign", "CDATA", vertiAlign);
// letra da cell
String fontStyle = "" + stylableCell.getFont().getStyle(); // style
attributes.addAttribute("", "", "fontStyle", "CDATA", fontStyle);
String fontSize = "" + stylableCell.getFont().getSize(); // size
attributes.addAttribute("", "", "fontSize", "CDATA", fontSize);
String fontName = "" + stylableCell.getFont().getName(); // font name
attributes.addAttribute("", "", "fontName", "CDATA", fontName);
String foregColor = "" + stylableCell.getForegroundColor().getRGB(); // foreground color
attributes.addAttribute("", "", "fgColor", "CDATA", foregColor);
String backgColor = "" + stylableCell.getBackgroundColor().getRGB(); // background color
attributes.addAttribute("", "", "bgColor", "CDATA", backgColor);
// bordas da cell
String left = "" + stylableCell.getBorder().getBorderInsets(null).left; // xml left
attributes.addAttribute("", "", "left", "CDATA", left);
String right = "" + stylableCell.getBorder().getBorderInsets(null).right; // xml right
attributes.addAttribute("", "", "right", "CDATA", right);
String top = "" + stylableCell.getBorder().getBorderInsets(null).top; // xml top
attributes.addAttribute("", "", "top", "CDATA", top);
String bottom = "" + stylableCell.getBorder().getBorderInsets(null).bottom; // xml bottom
attributes.addAttribute("", "", "bottom", "CDATA", bottom);
String content = "" + cell.getContent(); // conteudo da célula
attributes.addAttribute("", "", "content", "CDATA", content);
String address = "" + cell.getAddress(); //address
attributes.addAttribute("", "", "address", "CDATA", address);
String row = "" + cell.getAddress().getRow(); // linhas
attributes.addAttribute("", "", "row", "CDATA", row);
String column = "" + cell.getAddress().getColumn(); // colunas
attributes.addAttribute("", "", "column", "CDATA", column);
transHandler.startElement("", "", "cell", attributes); //<cell>
transHandler.endElement("", "", "cell"); //</cell>
}
} catch (SAXException ex) {
ex.getMessage();
}
}
try {
transHandler.endElement("", "", "spreadsheet"); //</spreadsheet>
} catch (SAXException ex) {
ex.getMessage();
}
}
try {
transHandler.endElement("", "", "workbook"); //</workbook>
transHandler.endDocument(); //fim documento
writer.close();
} catch (SAXException sasex) {
sasex.getMessage();
} catch (IOException ex) {
ex.getMessage();
}
StringWriter strWriter = (StringWriter) strResult.getWriter();
StringBuffer strBuffer = strWriter.getBuffer();
String xmlDoc = strBuffer.toString();
/*Escreve o ficheiro XML*/
PrintWriter printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
printWriter.write(xmlDoc);
printWriter.close();
this.xml = xmlDoc;
System.out.println("Gravado com sucesso!");
}
/*Metodo carregarSchema, recebe uma string com o nome do ficheiro XSD
* que pretende carregar.
* return Schema;*/
private static Schema carregarSchema(String name) {
Schema s = null;
try {
String lang = XMLConstants.W3C_XML_SCHEMA_NS_URI;
SchemaFactory factory = SchemaFactory.newInstance(lang);
s = factory.newSchema(new File(name));
} catch (Exception e) {
System.out.println(e.toString());
}
return s;
}
/*Metodo validarXml, recebe um Schema e um Document e valida
* o ficheiro XML com o XSD correspondente*/
private static boolean validarXml(Schema schema, Document document) {
try {
Validator valida = schema.newValidator();
valida.validate(new DOMSource(document));
System.out.println("Validação efectuada com sucesso!");
return true;
} catch (Exception ex) {
System.out.println("Validação encontrou erros! Ficheiro defeituoso.");
System.out.println(ex.toString());
return false;
}
}
}
PS:我是葡萄牙人,所以这里写的一些东西是葡萄牙语:p