0

I have an XML file with many tags that carry the same info, but are required by a service I'm trying to use.

<request>
    <first>{firstName}</first>
    <first_1>{firstName}</first_1>
    <first_2>{firstName</first_2>
</request>

In order to save time, I just want to be able to load the XML file and override all values in curly braces with the matching variable name such that:

val firstName = Bob
val myXML = XML.loadFile("path_to_file")
// TODO: myXML.override("firstName", firstName)

Would yield the XML:

<request>
    <first>Bob</first>
    <first_1>Bob</first_1>
    <first_2>Bob</first_2>
</request>

Any thoughts on how to do this?

1 Answer 1

1

Here is an example assuming that the variables can be stored in a standard Map.

For demonstration purposes, I added a "lastName" so there will be multiple variables.

Note that you can open and read the file into a variable such as xml, with Source.fromFile(filename).getLines.mkString or something equivalent.

Docs for Map include the foldLeft method description, but in general, it can be used to repeatedly apply a function to an initial value (xml in this case), given a collection (vars in this case) which provides parameters to this function.

val vars = Map("firstName" -> "Sally", "lastName" -> "Dunn")
val xml = """<request>
    <first>{firstName}</first>
    <first_1>{firstName}</first_1>
    <last_2>{lastName}</last_2>
</request>"""

// entry is a Map entry (or Tuple)
vars.foldLeft(xml)((res, entry) => res.replace("{" + entry._1 + "}", entry._2))

Result:

<request>
    <first>Sally</first>
    <first_1>Sally</first_1>
    <last_2>Dunn</last_2>
</request>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.