Document doc = builder.build(input, null);
String expected = "<n1:elem2 xmlns:n1=\"http://example.net\" xml:lang=\"en\">"
+ "<n3:stuff xmlns:n3=\"ftp://example.org\"></n3:stuff></n1:elem2>";
ByteArrayOutputStream out = new ByteArrayOutputStream();
Canonicalizer canonicalizer = new Canonicalizer(out,
Canonicalizer.EXCLUSIVE_XML_CANONICALIZATION_WITH_COMMENTS);
XPathContext context = new XPathContext("n1", "http://example.net");
canonicalizer.write(doc.query(" (//. | //@* | //namespace::*)[ancestor-or-self::n1:elem2]", context));
byte[] result = out.toByteArray();
out.close();
String s = new String(out.toByteArray(), "UTF8");
assertEquals(expected, s);