Apr
21
2011
xml-matchers - Hamcrest Matchers for XML
I recently published a small, open source project that I’ve been messing around with for probably close to two years now but never got around to cleaning up and publishing. It’s called xml-matchers and is a collection of Hamcrest matchers for matching against XML documents. I primarily created it for testing but I’m sure you could find other uses for it. The project is hosted at Google Code: http://code.google.com/p/xml-matchers/.
The matchers allow you to do things like:
Source xml = ... assertThat(xml, hasXPath("/mountains/mountain")); Node xml = ... assertThat( the(xml), hasXPath("count(/mountains/mountain)", returningANumber(), greaterThanOrEqualTo(2d))); String xml = "<mountains><mountain>K2</mountain></mountains>"; String xmlWithSpaceWrappingText = "<mountains><mountain>\n\tK2\n\t </mountain></mountains>"; assertThat(the(xml), isEquivalentTo(the(xmlWithSpaceWrappingText))); Schema schema = w3cXmlSchemaFromClasspath("org/xmlmatchers/validation/example.xsd"); String xml = "<person private=\"true\"><name>Dave</name></person>"; assertThat(the(xml), conformsTo(schema));