My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package fourty2ia.builder;

import org.w3c.dom.Element;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.util.Stack;

public class XmlDocumentBuilder {

private Document document;

private Stack<Element> stack;

public XmlDocumentBuilder(DocumentBuilderFactory docBuilderFactory)
throws ParserConfigurationException {

this.document = docBuilderFactory.newDocumentBuilder().newDocument();
stack = new Stack<Element>();

}

public XmlDocumentBuilder() throws ParserConfigurationException {
this(DocumentBuilderFactory.newInstance());
}

public Document build(){
return document;
}

public XmlDocumentBuilder beginElement(String name){

Element elem = document.createElement(name);

// if stack empty, then we have the root element
if(stack.isEmpty()){
document.appendChild(elem);
}
else {
stack.peek().appendChild(elem);
}

stack.push(elem);

return this;
}

public XmlDocumentBuilder endElement(){

if(stack.isEmpty()){
throw new IllegalStateException("No matching beginElement()");
}
stack.pop();

return this;
}

public XmlDocumentBuilder attr(String name,String value){
if(stack.isEmpty()){
throw new IllegalStateException("Empty stack");
}
stack.peek().setAttribute(name,value);

return this;
}

public XmlDocumentBuilder attr(String name,Object value){
return attr(name,value.toString());
}

public XmlDocumentBuilder text(String text){
if(stack.isEmpty()){
throw new IllegalStateException("Empty Stack");
}
stack.peek().appendChild(document.createTextNode(text));
return this;
}

public XmlDocumentBuilder element(String name,String ... attrs){
if(attrs.length % 2 != 0){
throw new IllegalArgumentException("Attribute name without value");
}

beginElement(name);
return endElement();
}

public XmlDocumentBuilder element(String name){
beginElement(name);
return endElement();
}
}

Change log

r4 by l.girndt on Jul 21, 2009   Diff
initial example for the builder blog entry
Go to: 
Project members, sign in to write a code review

Older revisions

All revisions of this file

File info

Size: 2308 bytes, 93 lines
Powered by Google Project Hosting