99import static org .hamcrest .xml .HasXPath .hasXPath ;
1010import org .w3c .dom .Document ;
1111
12+ import javax .xml .namespace .NamespaceContext ;
1213import javax .xml .parsers .DocumentBuilder ;
1314import javax .xml .parsers .DocumentBuilderFactory ;
1415import java .io .ByteArrayInputStream ;
16+ import java .util .HashSet ;
17+ import java .util .Iterator ;
1518
1619/**
1720 * @author Joe Walnes
@@ -25,6 +28,7 @@ protected void setUp() throws Exception {
2528 + "<root type='food'>\n "
2629 + " <something id='a'><cheese>Edam</cheese></something>\n "
2730 + " <something id='b'><cheese>Cheddar</cheese></something>\n "
31+ + " <f:foreignSomething xmlns:f=\" http://cheese.com\" milk=\" camel\" >Caravane</f:foreignSomething>\n "
2832 + "</root>\n "
2933 );
3034 }
@@ -47,6 +51,31 @@ public void testFailsIfNodeIsMissing() throws Exception {
4751 assertThat (xml , not (hasXPath ("//something[@id='c']/cheese" )));
4852 }
4953
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+
5079 public void testThrowsIllegalArgumentExceptionIfGivenIllegalExpression () {
5180 try {
5281 hasXPath ("\\ g:dfgd::DSgf/root/something[2]/cheese" , equalTo ("blah" ));
@@ -65,6 +94,7 @@ public void testDescribesItself() throws Exception {
6594
6695 private Document parse (String xml ) throws Exception {
6796 DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory .newInstance ();
97+ documentBuilderFactory .setNamespaceAware (true );
6898 DocumentBuilder documentBuilder = documentBuilderFactory .newDocumentBuilder ();
6999 return documentBuilder .parse (new ByteArrayInputStream (xml .getBytes ()));
70100 }
0 commit comments