Allow individual attributes in an XML element to be documented

Documenting an XML attribute in the XML payload leads to a
NullPointerException since no parent nodes exists for an XML
attribute. Rather than always trying to remove a node from its parent,
this commit changes the logic to apply special treament to nodes that
are attributes and remove the attribute from its owning element
instead.

Closes gh-167
This commit is contained in:
cschaetzlein
2015-11-16 16:15:04 +01:00
committed by Andy Wilkinson
parent 75085477b6
commit 58b992d99e
2 changed files with 25 additions and 1 deletions

View File

@@ -34,6 +34,7 @@ import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
@@ -115,7 +116,15 @@ class XmlContentHandler implements ContentHandler {
}
for (int i = 0; i < matchingNodes.getLength(); i++) {
Node node = matchingNodes.item(i);
node.getParentNode().removeChild(node);
if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
Attr attr = (Attr) node;
attr.getOwnerElement().removeAttributeNode(attr);
}
else {
node.getParentNode().removeChild(node);
}
}
}
if (payload.getChildNodes().getLength() > 0) {

View File

@@ -192,6 +192,21 @@ public class ResponseFieldsSnippetTests {
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)
.build());
}
@Test
public void undocumentedXmlWithAttributeResponseField() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown
.expectMessage(equalTo("The following parts of the payload were not"
+ " documented:\r\n<a>\r\n <b>5</b>\r\n</a>\r\n"));
new ResponseFieldsSnippet(Arrays.asList(new FieldDescriptor("/a/b/@id").type("").description("")))
.document(new OperationBuilder("undocumented-xml-response-field",
this.snippet.getOutputDirectory())
.response()
.content("<a><b id=\"1\">5</b></a>")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)
.build());
}
@Test
public void xmlResponseFieldWithNoType() throws IOException {