{"record":{"id":"c98f7ccbf0d17bbe","repo":"karatelabs/karate","slug":"fromstring-xml-parse-failed","errorCode":null,"errorMessage":"fromString XML parse failed: {}","messagePattern":"fromString XML parse failed: (.+?)","errorType":"console","errorClass":null,"httpStatus":null,"severity":"warning","filePath":"karate-core/src/main/java/io/karatelabs/core/KarateJsUtils.java","lineNumber":799,"sourceCode":"            if (args.length == 0 || args[0] == null) {\n                return null;\n            }\n            String text = args[0].toString();\n            if (text.isEmpty()) {\n                return text;\n            }\n            if (StringUtils.looksLikeJson(text)) {\n                try {\n                    return Json.of(text).value();\n                } catch (Exception e) {\n                    logger.warn(\"fromString JSON parse failed: {}\", e.getMessage());\n                    return text;\n                }\n            } else if (StringUtils.isXml(text)) {\n                try {\n                    return Xml.toXmlDoc(text);\n                } catch (Exception e) {\n                    logger.warn(\"fromString XML parse failed: {}\", e.getMessage());\n                    return text;\n                }\n            }\n            return text;\n        };\n    }\n\n    /**\n     * Auto-detect MIME type from data object.\n     */\n    static String detectMimeType(Object obj) {\n        if (obj instanceof Map || obj instanceof List) {\n            return \"application/json\";\n        } else if (obj instanceof Node) {\n            return \"application/xml\";\n        } else if (obj instanceof byte[] bytes) {\n            return sniffBytesMime(bytes);\n        } else {","sourceCodeStart":781,"sourceCodeEnd":817,"githubUrl":"https://github.com/karatelabs/karate/blob/a22eb90246d958d15a47bf436693d0121ad2812d/karate-core/src/main/java/io/karatelabs/core/KarateJsUtils.java#L781-L817","documentation":"The XML branch of karate's fromString coercion: when a string is detected as XML (StringUtils.isXml), Xml.toXmlDoc converts it to a document node. If that conversion throws, 'fromString XML parse failed' is logged and the original string is returned as-is — a non-fatal fallback so callers receive the raw text rather than an exception.","triggerScenarios":"Calling karate.fromString(...) (or a coercion path using it) with a string that looks like XML but is not well-formed: unclosed tags, mismatched tags, invalid entity references, XML declaration issues, multiple root elements, or encoding/character problems.","commonSituations":"Scraping XML from an upstream service that returns malformed XML; building XML by string concatenation and forgetting to close a tag; HTML (not XHTML) pasted where strict XML parsing is expected; SOAP payloads truncated by an earlier transformation.","solutions":["Fix the input so it is well-formed XML (close all tags, single root, valid entities).","Validate the XML with a parser/linter (xmllint or Xml parsing in isolation) before passing it to fromString.","If the content is HTML, escape/convert it to XHTML or use an HTML-tolerant parser instead of fromString.","Read the logged e.getMessage() to find the exact malformed location in the document.","Handle the fallback in caller code: check whether the result is a String vs a document and branch accordingly."],"exampleFix":"// before\nvar doc = karate.fromString('<a><b>text</a>'); // mismatched tag -> warning, returns raw string\n\n// after\nvar doc = karate.fromString('<a><b>text</b></a>'); // well-formed -> XML doc node","handlingStrategy":"validation","validationCode":"// JS: well-formedness smoke test before fromString\nfunction looksWellFormedXml(s) {\n  return /^\\s*<\\/?[\\w:-]+[\\s\\S]*>\\s*$/.test(s) &&\n    s.replace(/<\\/[\\w:-]+>/g, '').length !== s.length; // has at least one close tag\n}","typeGuard":"function isXmlDoc(v) { return v !== null && typeof v === 'object' && typeof v !== 'string'; }","tryCatchPattern":"// fromString returns the raw string on XML failure; check the result type\nvar doc = karate.fromString(xmlText);\nif (typeof doc === 'string') {\n  // XML parse failed; handle malformed input explicitly\n}","preventionTips":["Validate XML fixtures with xmllint or a parser in CI before use.","Never build XML by naive string concatenation; use an XML builder or template with escaping.","Don't feed HTML into fromString expecting XML parsing — convert to XHTML first.","Read the logged e.getMessage() to locate the malformed region of the document."],"tags":["xml","parsing","karate","fallback"],"backgroundTag":"invalid-argument-format","analyzedSha":"a22eb90246d958d15a47bf436693d0121ad2812d","analyzedAt":"2026-09-12T09:01:00.220Z","contentChangedAt":"2026-09-12T09:01:00.220Z","schemaVersion":2},"datasetVersion":"2026-09-19T12:17:13.211Z"}