Reading and Writing XML

Once we get an XML document in memory, we know how to parse it. The next step is to figure out a way to get an XML document loaded into the program and to save an in-memory document to a file. As an example, let’s load an XML file that contains symbols and units, increase the units by 1, and store the updated content back into another XML file. Let’s first tackle the step of loading the file.

Here’s a sample file stocks.xml that we’ll use:

UsingScala/stocks.xml
 
<symbols>
 
<symbol​ ticker=​"AAPL"​​>​​<units>​200​</units>​​</symbol>
 
<symbol​ ticker=​"ADBE"​​>​​<units>​125​</units>​​</symbol>
 
<symbol​ ticker=​"ALU"​​>​​<units>​150​</units>​​</symbol>
 
<symbol​ ticker=​"AMD"​​>​​<units>​150​</units>​​</symbol> ...

Get Pragmatic Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.