1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.jxpath.ri.model.dom;
18
19 import org.apache.commons.jxpath.AbstractFactory;
20 import org.apache.commons.jxpath.JXPathContext;
21 import org.apache.commons.jxpath.ri.model.XMLModelTestCase;
22 import org.apache.commons.jxpath.xml.DocumentContainer;
23
24 import org.w3c.dom.Attr;
25 import org.w3c.dom.Document;
26 import org.w3c.dom.Element;
27 import org.w3c.dom.Node;
28 import org.w3c.dom.NodeList;
29
30
31
32
33
34
35
36
37 public class DOMModelTest extends XMLModelTestCase {
38
39 protected String getModel() {
40 return DocumentContainer.MODEL_DOM;
41 }
42
43 protected AbstractFactory getAbstractFactory() {
44 return new TestDOMFactory();
45 }
46
47 public void testGetNode() {
48 assertXPathNodeType(context, "/", Document.class);
49 assertXPathNodeType(context, "/vendor/location", Element.class);
50 assertXPathNodeType(context, "//location/@name", Attr.class);
51 assertXPathNodeType(context, "//vendor", Element.class);
52 }
53
54 public void testGetElementDescendantOrSelf() {
55 JXPathContext childContext = context.getRelativeContext(context.getPointer("/vendor"));
56 assertTrue(childContext.getContextBean() instanceof Element);
57 assertXPathNodeType(childContext, "//vendor", Element.class);
58 }
59
60 protected String getXMLSignature(
61 Object node,
62 boolean elements,
63 boolean attributes,
64 boolean text,
65 boolean pi)
66 {
67 StringBuffer buffer = new StringBuffer();
68 appendXMLSignature(buffer, node, elements, attributes, text, pi);
69 return buffer.toString();
70 }
71
72 private void appendXMLSignature(
73 StringBuffer buffer,
74 Object object,
75 boolean elements,
76 boolean attributes,
77 boolean text,
78 boolean pi)
79 {
80 Node node = (Node) object;
81 int type = node.getNodeType();
82 switch (type) {
83 case Node.DOCUMENT_NODE :
84 buffer.append("<D>");
85 appendXMLSignature(
86 buffer,
87 node.getChildNodes(),
88 elements,
89 attributes,
90 text,
91 pi);
92 buffer.append("</D");
93 break;
94
95 case Node.ELEMENT_NODE :
96 String tag = elements ? ((Element) node).getTagName() : "E";
97 buffer.append("<");
98 buffer.append(tag);
99 buffer.append(">");
100 appendXMLSignature(
101 buffer,
102 node.getChildNodes(),
103 elements,
104 attributes,
105 text,
106 pi);
107 buffer.append("</");
108 buffer.append(tag);
109 buffer.append(">");
110 break;
111
112 case Node.TEXT_NODE :
113 case Node.CDATA_SECTION_NODE :
114 if (text) {
115 String string = node.getNodeValue();
116 string = string.replace('\n', '=');
117 buffer.append(string);
118 }
119 break;
120 }
121 }
122
123 private void appendXMLSignature(
124 StringBuffer buffer,
125 NodeList children,
126 boolean elements,
127 boolean attributes,
128 boolean text,
129 boolean pi)
130 {
131 for (int i = 0; i < children.getLength(); i++) {
132 appendXMLSignature(
133 buffer,
134 children.item(i),
135 elements,
136 attributes,
137 text,
138 pi);
139 }
140 }
141 }