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

Allow document type definitions to be included when parsing XML for body matching #239

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,15 @@ import com.itv.scalapact.shared.utils.Helpers.{
safeStringToDouble
}

import javax.xml.parsers.SAXParserFactory
import scala.util.Try
import scala.xml.{Elem, Node, XML}
import scala.xml.factory.XMLLoader
import scala.xml.{Elem, Node}

object MatchIr {

private val XML: XMLLoader[Elem] = createXMLParser()

def fromXmlString(xmlString: String): Option[IrNode] =
Try(XML.loadString(xmlString)).toOption.map(fromXml)

Expand All @@ -21,6 +26,13 @@ object MatchIr {
def fromJSON(fromJson: String => Option[IrNode])(jsonString: String): Option[IrNode] =
fromJson(jsonString)

private def createXMLParser(): XMLLoader[Elem] = {
val sAXParserFactory = SAXParserFactory.newInstance()
sAXParserFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false);
val saxParser = sAXParserFactory.newSAXParser()
xml.XML.withSAXParser(saxParser)
}

private def convertAttributes(attributes: Map[String, String], pathToParent: IrNodePath): IrNodeAttributes =
attributes.toList.reverse
.map {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,28 @@ class MatchIrSpec extends AnyFunSpec with Matchers {

}

it("should be able to convert xml with a document type definition") {
val xml: String =
"""<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE animals [<!ELEMENT animals (alligator)*><!ELEMENT alligator (#PCDATA)><!ATTLIST alligator name CDATA #REQUIRED>]><animals><alligator name="Mary"/></animals>""".stripMargin

val ir: IrNode =
IrNode(
"animals",
IrNode("alligator")
.withAttributes(
IrNodeAttributes(
Map(
"name" -> IrNodeAttribute(IrStringNode("Mary"), IrNodePathEmpty <~ "animals" <~ "alligator" <@ "name")
)
)
)
.withPath(IrNodePathEmpty <~ "animals" <~ "alligator")
.markAsXml
).withPath(IrNodePathEmpty <~ "animals").markAsXml

check(MatchIr.fromXmlString(xml).get =<>= ir)
}

it("should be able to convert one node with content") {

val xml: String = <fish>haddock</fish>.toString()
Expand Down