diff --git a/karate-core/src/main/java/com/intuit/karate/XmlUtils.java b/karate-core/src/main/java/com/intuit/karate/XmlUtils.java index 1dd570fd7..68dd2d79e 100755 --- a/karate-core/src/main/java/com/intuit/karate/XmlUtils.java +++ b/karate-core/src/main/java/com/intuit/karate/XmlUtils.java @@ -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); try { DocumentBuilder builder = factory.newDocumentBuilder(); DtdEntityResolver dtdEntityResolver = new DtdEntityResolver(); @@ -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 map = new LinkedHashMap<>(childElementCount); NodeList nodes = node.getChildNodes(); diff --git a/karate-core/src/test/java/com/intuit/karate/core/ScenarioEngineTest.java b/karate-core/src/test/java/com/intuit/karate/core/ScenarioEngineTest.java index 8268cc2ca..b065a4934 100644 --- a/karate-core/src/test/java/com/intuit/karate/core/ScenarioEngineTest.java +++ b/karate-core/src/test/java/com/intuit/karate/core/ScenarioEngineTest.java @@ -232,6 +232,11 @@ void testEvalXmlAndXpath() { matchEquals("temp", "baz"); assign("temp", "get myMap /root/foo"); matchEquals("temp", "baz"); + + // preserves whitespace in content + assign("myXml", " baz "); + value = engine.evalKarateExpression("$myXml/root/foo/bar"); + matchEval(value.getValue(), " baz "); } @Test diff --git a/karate-demo/src/test/java/demo/xml/preserve-whitespace.feature b/karate-demo/src/test/java/demo/xml/preserve-whitespace.feature new file mode 100644 index 000000000..5cf0c70df --- /dev/null +++ b/karate-demo/src/test/java/demo/xml/preserve-whitespace.feature @@ -0,0 +1,9 @@ +Feature: Preserve white space in text content +Scenario: + * def xml = + """ + + myValue + + """ + * match karate.xmlPath(xml, '/myRoot/myNode') == ' myValue ' \ No newline at end of file