일하다가 이것때문에 시간을 마니 잡아먹어서 기억할 겸 메모한다.
처음에는 org.apache.xerces.dom.DocumentImpl와 org.w3c.dom.Document, DOMImplementationRegistry, DOMImplementationLS 를 사용했는데(how-can-i-build-an-html-org-w3c-dom-document),
라이브러리가 꼬여서 다른방법이 없나 찾아보다가 DocumentBuilder,TransformerFactory를 사용하는 방법으로 구현했다.
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class CustomTest {
public CustomTest() {
}
public String makeElement() {
StringBuffer sb = new StringBuffer();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Document htmlDoc = builder.newDocument();
Element ulElement = htmlDoc.createElement("ul");
Element liElement = htmlDoc.createElement("li");
Element aElement = htmlDoc.createElement("a");
aElement.setAttribute("href", "#none");
aElement.setTextContent("Test");
liElement.appendChild(aElement);
ulElement.appendChild(liElement);
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer =null;
StringWriter buffer = null;
try {
transformer = transFactory.newTransformer();
buffer = new StringWriter();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(ulElement),
new StreamResult(buffer));
} catch (TransformerConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sb.append(buffer);
return sb.toString();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CustomTest cm = new CustomTest();
System.out.println("start!!");
//StringBuffer sb = new StringBuffer();
//sb.append(menu.getHtmlHelpPage(""));
System.out.print(cm.makeElement());
}
}
결과:
<ul>
<li>
<a href=”#none”>Test</a>
</li>
</ul>