Skip to content

Commit

Permalink
Introduce "Saxy.encode!/2" and "Saxy.encode_to_iodata!/2"
Browse files Browse the repository at this point in the history
  • Loading branch information
qcam committed Jul 13, 2018
1 parent c8fb37d commit a43bf8e
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 1 deletion.
55 changes: 54 additions & 1 deletion lib/saxy.ex
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,11 @@ defmodule Saxy do
"""

alias Saxy.{Parser, State}
alias Saxy.{
Encoder,
Parser,
State
}

@doc ~S"""
Parses XML binary data.
Expand Down Expand Up @@ -206,4 +210,53 @@ defmodule Saxy do

Parser.parse_document(<<>>, stream, state)
end

@doc """
Encodes a simple form XML element into string.
This function encodes an element in simple form format and a prolog to an XML document.
## Examples
iex> import Saxy.XML
iex> root = element(:foo, [{"foo", "bar"}], "bar")
iex> prolog = [version: "1.0"]
iex> Saxy.encode!(root, prolog)
"<?xml version=\\"1.0\\"?><foo foo=\\"bar\\">bar</foo>"
"""

@spec encode!(root :: Saxy.XML.element(), prolog :: Saxy.Prolog.t() | Keyword.t()) :: String.t()

def encode!(root, prolog \\ []) do
root
|> Encoder.encode_to_iodata(prolog)
|> IO.iodata_to_binary()
end

@doc """
Encodes a simple form element into IO data.
Same as `encode!/2` but this encodes the document into IO data.
## Examples
iex> import Saxy.XML
iex> root = element(:foo, [{"foo", "bar"}], "bar")
iex> prolog = [version: "1.0"]
iex> Saxy.encode_to_iodata!(root, prolog)
[
['<?xml', [32, 'version', 61, 34, "1.0", 34], [], [], '?>'],
[60, "foo", 32, "foo", 61, 34, "bar", 34],
62,
["bar"],
[60, 47, "foo", 62]
]
"""
@spec encode_to_iodata!(root :: Saxy.XML.element(), prolog :: Saxy.Prolog.t() | Keyword.t()) :: iodata()

def encode_to_iodata!(root, prolog \\ []) do
Encoder.encode_to_iodata(root, prolog)
end
end
20 changes: 20 additions & 0 deletions test/saxy_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -109,5 +109,25 @@ defmodule SaxyTest do
assert HandlerError.message(error) == "unexpected return :something_wrong in :start_document event handler"
end

describe "encode!/2" do
import Saxy.XML

test "encodes XML document into string" do
root = element("foo", [], "foo")
assert Saxy.encode!(root) == ~s(<?xml version="1.0"?><foo>foo</foo>)
end
end

describe "encode_to_iodata!/2" do
import Saxy.XML

test "encodes XML document into IO data" do
root = element("foo", [], "foo")
assert xml = Saxy.encode_to_iodata!(root)
assert is_list(xml)
assert IO.iodata_to_binary(xml) == ~s(<?xml version="1.0"?><foo>foo</foo>)
end
end

def convert_entity("unknown"), do: "known"
end

0 comments on commit a43bf8e

Please sign in to comment.