diff --git a/README.md b/README.md index 976bdcc..4cc368a 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,27 @@ Outputs Hello, world! ``` +### Encoding + +While the output is always UTF-8 and has to be converted in another place, you can override the encoding statement in the xml declaration +with the `encoding` option: + +```elixir +import XmlBuilder + +[XmlBuilder.element(:oldschool, [])] +|> XmlBuilder.document() +|> XmlBuilder.generate(encoding: "ISO-8859-1") +|> :unicode.characters_to_binary(:unicode, :latin1) +``` + +Outputs + +```xml + + +``` + ### Formatting With indentation: `XmlBuilder.generate(doc, format: :indent)` diff --git a/lib/xml_builder.ex b/lib/xml_builder.ex index 80774c9..eb37b7d 100644 --- a/lib/xml_builder.ex +++ b/lib/xml_builder.ex @@ -210,12 +210,17 @@ defmodule XmlBuilder do iex> XmlBuilder.generate({:name, nil, [{:first, nil, "Steve"}]}) "\\n Steve\\n" + + iex> XmlBuilder.generate(:xml_decl, encoding: "ISO-8859-1") + ~s|| """ def generate(any, options \\ []), do: format(any, 0, options) |> IO.chardata_to_string - defp format(:xml_decl, 0, _options), - do: ~s|| + defp format(:xml_decl, 0, options) do + encoding = Keyword.get(options, :encoding, "UTF-8") + ~s|| + end defp format({:doctype, {:system, name, system}}, 0, _options), do: [''] diff --git a/test/xml_builder_test.exs b/test/xml_builder_test.exs index daace90..32ef1e0 100644 --- a/test/xml_builder_test.exs +++ b/test/xml_builder_test.exs @@ -61,6 +61,24 @@ defmodule XmlBuilderTest do expectation = "\n\ttest_value\n" assert XmlBuilder.generate(input(), whitespace: "\t") == expectation end + + test "encoding defaults to UTF-8" do + expectation = ~s|| + assert XmlBuilder.generate(:xml_decl) == expectation + end + + test "encoding option is used" do + expectation = ~s|| + assert XmlBuilder.generate(:xml_decl, encoding: "ISO-8859-1") == expectation + end + + test "encoding option works with other options" do + xml = [XmlBuilder.element(:oldschool, [])] + |> XmlBuilder.document() + |> XmlBuilder.generate(format: :indent, encoding: "ISO-8859-1") + expectation = ~s|\n| + assert xml == expectation + end end test "element with content" do