Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2454: Preserve whitespace in node value when using karate.xmlPath #2496

Merged
merged 1 commit into from
Feb 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion karate-core/src/main/java/com/intuit/karate/XmlUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ public static Document toXmlDoc(String xml) {
public static Document toXmlDoc(String xml, boolean namespaceAware) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
factory.setIgnoringElementContentWhitespace(false);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

false is the default setting. So nothing changes in the current document parsing behavior.
Added the above line to make the behavior explicit.

try {
DocumentBuilder builder = factory.newDocumentBuilder();
DtdEntityResolver dtdEntityResolver = new DtdEntityResolver();
Expand Down Expand Up @@ -294,7 +295,9 @@ public static int getChildElementCount(Node node) {
private static Object getElementAsObject(Node node, boolean removeNamespace) {
int childElementCount = getChildElementCount(node);
if (childElementCount == 0) {
return StringUtils.trimToNull(node.getTextContent());
String textContent = node.getTextContent();
return StringUtils.isBlank(textContent) ? null:
textContent;
}
Map<String, Object> map = new LinkedHashMap<>(childElementCount);
NodeList nodes = node.getChildNodes();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,11 @@ void testEvalXmlAndXpath() {
matchEquals("temp", "<foo><bar>baz</bar></foo>");
assign("temp", "get myMap /root/foo");
matchEquals("temp", "<foo><bar>baz</bar></foo>");

// preserves whitespace in content
assign("myXml", "<root><foo><bar> baz </bar></foo></root>");
value = engine.evalKarateExpression("$myXml/root/foo/bar");
matchEval(value.getValue(), " baz ");
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Feature: Preserve white space in text content
Scenario:
* def xml =
"""
<myRoot xml:space="preserve">
<myNode> myValue </myNode>
</myRoot>
"""
* match karate.xmlPath(xml, '/myRoot/myNode') == ' myValue '