9
9
import static org .hamcrest .xml .HasXPath .hasXPath ;
10
10
import org .w3c .dom .Document ;
11
11
12
+ import javax .xml .namespace .NamespaceContext ;
12
13
import javax .xml .parsers .DocumentBuilder ;
13
14
import javax .xml .parsers .DocumentBuilderFactory ;
14
15
import java .io .ByteArrayInputStream ;
16
+ import java .util .HashSet ;
17
+ import java .util .Iterator ;
15
18
16
19
/**
17
20
* @author Joe Walnes
@@ -25,6 +28,7 @@ protected void setUp() throws Exception {
25
28
+ "<root type='food'>\n "
26
29
+ " <something id='a'><cheese>Edam</cheese></something>\n "
27
30
+ " <something id='b'><cheese>Cheddar</cheese></something>\n "
31
+ + " <f:foreignSomething xmlns:f=\" http://cheese.com\" milk=\" camel\" >Caravane</f:foreignSomething>\n "
28
32
+ "</root>\n "
29
33
);
30
34
}
@@ -47,6 +51,31 @@ public void testFailsIfNodeIsMissing() throws Exception {
47
51
assertThat (xml , not (hasXPath ("//something[@id='c']/cheese" )));
48
52
}
49
53
54
+ public void testMatchesWithNamespace () throws Exception {
55
+ NamespaceContext ns = new NamespaceContext () {
56
+ public String getNamespaceURI (String prefix ) {
57
+ return ("cheese" .equals (prefix ) ? "http://cheese.com" : null );
58
+ }
59
+
60
+ public String getPrefix (String namespaceURI ) {
61
+ return ("http://cheese.com" .equals (namespaceURI ) ? "cheese" : null );
62
+ }
63
+
64
+ public Iterator getPrefixes (String namespaceURI ) {
65
+ HashSet <String > prefixes = new HashSet <String >();
66
+ String prefix = getPrefix (namespaceURI );
67
+ if (prefix != null ) {
68
+ prefixes .add (prefix );
69
+ }
70
+ return prefixes .iterator ();
71
+ }
72
+ };
73
+
74
+ assertThat (xml , hasXPath ("//cheese:foreignSomething" , ns ));
75
+ assertThat (xml , hasXPath ("//cheese:foreignSomething/@milk" , ns , equalTo ("camel" )));
76
+ assertThat (xml , hasXPath ("//cheese:foreignSomething/text()" , ns , equalTo ("Caravane" )));
77
+ }
78
+
50
79
public void testThrowsIllegalArgumentExceptionIfGivenIllegalExpression () {
51
80
try {
52
81
hasXPath ("\\ g:dfgd::DSgf/root/something[2]/cheese" , equalTo ("blah" ));
@@ -65,6 +94,7 @@ public void testDescribesItself() throws Exception {
65
94
66
95
private Document parse (String xml ) throws Exception {
67
96
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory .newInstance ();
97
+ documentBuilderFactory .setNamespaceAware (true );
68
98
DocumentBuilder documentBuilder = documentBuilderFactory .newDocumentBuilder ();
69
99
return documentBuilder .parse (new ByteArrayInputStream (xml .getBytes ()));
70
100
}
0 commit comments