Extensible Markup Language - XML

XML parsing module offers Flows for parsing and processing parsed XML documents.

Artifacts

sbt
libraryDependencies += "com.lightbend.akka" %% "akka-stream-alpakka-xml" % "0.14"
Maven
<dependency>
  <groupId>com.lightbend.akka</groupId>
  <artifactId>akka-stream-alpakka-xml_2.12</artifactId>
  <version>0.14</version>
</dependency>
Gradle
dependencies {
  compile group: 'com.lightbend.akka', name: 'akka-stream-alpakka-xml_2.12', version: '0.14'
}

XML parsing

XML processing pipeline starts with an XmlParsing.parser flow which parses a stream of ByteStrings to XML parser events.

Scala
val parse = Flow[String]
  .map(ByteString(_))
  .via(XmlParsing.parser)
  .toMat(Sink.seq)(Keep.right)
Java
final Sink<String, CompletionStage<List<ParseEvent>>> parse = Flow.<String>create()
  .map(ByteString::fromString)
  .via(XmlParsing.parser())
  .toMat(Sink.seq(), Keep.right());

To parse an XML document run XML document source with this parser.

Scala
val doc = "<doc><elem>elem1</elem><elem>elem2</elem></doc>"
val resultFuture = Source.single(doc).runWith(parse)
Java
final String doc = "<doc><elem>elem1</elem><elem>elem2</elem></doc>";
final CompletionStage<List<ParseEvent>> resultStage = Source.single(doc).runWith(parse, materializer);

XML Subslice

Use XmlParsing.subslice to filter out all elements not corresponding to a certain path.

Scala
val parse = Flow[String]
  .map(ByteString(_))
  .via(XmlParsing.parser)
  .via(XmlParsing.subslice("doc" :: "elem" :: "item" :: Nil))
  .toMat(Sink.seq)(Keep.right)
Java
final Sink<String, CompletionStage<List<ParseEvent>>> parse = Flow.<String>create()
  .map(ByteString::fromString)
  .via(XmlParsing.parser())
  .via(XmlParsing.subslice(Arrays.asList("doc", "elem", "item")))
  .toMat(Sink.seq(), Keep.right());

To get a subslice of an XML document run XML document source with this parser.

Scala
val doc =
  """
    |<doc>
    |  <elem>
    |    <item>i1</item>
    |    <item><sub>i2</sub></item>
    |    <item>i3</item>
    |  </elem>
    |</doc>
  """.stripMargin
val resultFuture = Source.single(doc).runWith(parse)
Java
final String doc =
  "<doc>" +
  "  <elem>" +
  "    <item>i1</item>" +
  "    <item><sub>i2</sub></item>" +
  "     <item>i3</item>" +
  "  </elem>" +
  "</doc>";
final CompletionStage<List<ParseEvent>> resultStage = Source.single(doc).runWith(parse, materializer);
The source code for this page can be found here.