1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| Element e = textPane.getDocument().getDefaultRootElement();
SAXTransformerFactory tf = (SAXTransformerFactory)SAXTransformerFactory.newInstance();
TransformerHandler handler = tf.newTransformerHandler();
Transformer t = handler.getTransformer();
t.setOutputProperty(javax.xml.transform.OutputKeys.ENCODING, "UTF-16");
StringWriter sw = new StringWriter();
handler.setResult(new StreamResult(sw));
handler.startDocument();
parseElement(e, handler);
handler.endDocument();
...
private void parseElement(Element e, ContentHandler ch) {
try {
AttributeSet as = e.getAttributes();
AttributesImpl a = new AttributesImpl();
Enumeration ase = as.getAttributeNames();
while (ase.hasMoreElements()) {
Object name = ase.nextElement();
Object value = as.getAttribute(name);
a.addAttribute("", "", name.toString(), "string", value.toString());
}
ch.startElement("", "", "Element", a);
int ec = e.getElementCount();
if (ec == 0) {
int start = e.getStartOffset();
int len = e.getEndOffset() - start;
if (start < textPane.getDocument().getLength()) {
a = new AttributesImpl();
a.addAttribute("", "", "Offset", "string", Integer.toString(start));
try {
ch.startElement("", "", "Text", a);
String text = textPane.getDocument().getText(start, len);
char[] textChars = new char[text.length()];
text.getChars(0, text.length(), textChars, 0);
ch.characters(textChars, 0, text.length());
ch.endElement("", "", "Text");
} catch(BadLocationException ble) {
}
}
} else {
for (int i=0; i<ec; i++) {
parseElement(e.getElement(i), ch);
}
}
ch.endElement("", "", "Element");
} catch(SAXException saxe) {
saxe.printStackTrace();
}
} |
Partager