czrpb

czrpb

I would like to modify an XML file; meaning parsing and writing back out to file.

Lets make it simple: i want to uppercase all b elements with a name attribute.

ORIGINAL

<a>
   <b name="sam">text</b>
   <c name="sal">text</b>
   <b title="bob">text</b>
</a>

UPDATED

<a>
   <b name="SAM">text</b>
   <c name="sal">text</b>
   <b title="bob">text</b>
</a>

ive spent a reasonable amount of time searching for examples of reading and writing, thus updating an XML string/file but just can not seem to find anything.

sweet_xml has been great, but i cant see how to use it to modify and write an xml string (file).

What am I missing in the elixir ecosystem to read/transform/write XML?

thx!! << q

Showing Posts 1 to 8

zachallaun

zachallaun

I’d recommend looking at saxy, which is both a parser and encoder that should enable what you’re looking for.

czrpb

czrpb OP

thx! any links to examples?

czrpb

czrpb OP

ok, to answer my own question, here is what i have for my simple example; i hope it works with minimal changes on a complex one (with UTF chars in it too!)

Mix.install([
  {:saxy, "~> 1.4.0"}
])

defmodule ExampleHandler do
  @behaviour Saxy.Handler

  def handle_event(:start_element, {"b", [{"name", name}]}, state) do
    {:ok, state <> ~s|<b name="#{String.upcase(name)}">|}
  end

  def handle_event(:start_element, {tag, attrs}, state) do
    attrs = attrs
    |> Enum.map(fn {key, value} -> ~s|#{key}="#{value}"| end)
    |> Enum.join()

    {:ok, state <> "<#{tag} #{attrs}>"}
  end

  def handle_event(:end_element, tag, state) do
    {:ok, state <> "</#{tag}>"}
  end

  def handle_event(:characters, cdata, state) do
    {:ok, state <> cdata}
  end

  def handle_event(_, _, state), do: {:ok, state}
end

[xmlfile|_] = System.argv()

IO.puts("Processing #{xmlfile}")

{:ok, result} =
  Saxy.parse_stream(File.stream!(xmlfile), ExampleHandler, "")

result
|> IO.puts

execution:

$ cat example.xml        
<a>
   <b name="sam">text</b>
   <c name="sal">text</c>
   <b title="bob">text</b>
</a>

$ elixir xml.exs example.xml
Processing example.xml
<a >
   <b name="SAM">text</b>
   <c name="sal">text</c>
   <b title="bob">text</b>
</a>
zachallaun

zachallaun

Awesome! Glad you got it figured out.

A minor suggestion: use IO data instead of concatenating strings directly. IO data is a sort of composite data type meant for this exact use-case, where the result is modeled as an arbitrarily nested list of strings/characters/etc. In the example below, I’m using IO.chardata_to_string/1, but if you’re just writing it back out to a file and have no use for further string processing, you can actually pass the chardata directly to most (all?) IO functions!

For a super small example the runtime will be essentially the same, but using IO data will definitely be faster for large files (and I think the resulting code is a bit cleaner).

Mix.install([
  {:saxy, "~> 1.4.0"}
])

defmodule ExampleHandler do
  @behaviour Saxy.Handler

  def parse_stream!(xml_stream) do
    {:ok, rev_chardata} = Saxy.parse_stream(xml_stream, __MODULE__, [])

    rev_chardata
    |> Enum.reverse()
    |> IO.chardata_to_string()
  end

  def build(:open, tag, attrs) do
    encoded_attrs = Enum.map(attrs, fn {name, val} -> [" ", name, "=\"", val, "\""] end)
    ["<", tag, encoded_attrs, ">"]
  end

  def build(:close, tag) do
    ["</", tag, ">"]
  end

  def handle_event(:start_element, {"b", [{"name", name}]}, state) do
    {:ok, [build(:open, "b", [{"name", String.upcase(name)}]) | state]}
  end

  def handle_event(:start_element, {tag, attrs}, state) do
    {:ok, [build(:open, tag, attrs) | state]}
  end

  def handle_event(:end_element, tag, state) do
    {:ok, [build(:close, tag) | state]}
  end

  def handle_event(:characters, cdata, state) do
    {:ok, [cdata | state]}
  end

  def handle_event(_, _, state), do: {:ok, state}
end

[xmlfile | _] = System.argv()

IO.puts("Processing #{xmlfile}")

ExampleHandler.parse_stream!(File.stream!(xmlfile))
|> IO.puts()

Works fine with unicode too =)

> elixir saxy_example.exs example.xml
<a>
   <b name="SAM">π</b>
   <c name="sal">text</c>
   <b title="bob">text</b>
</a>
al2o3cr

al2o3cr

Don’t make XML by gluing together strings - it’s too easy to create bugs.

For instance, ExampleHandler will produce invalid XML when given this document:

<something>
  <b name="foo">blargh</b>
  <b name="foo&quot;bar">baz</b>
  <z nothing="nope" />
</something>

the output fails to re-escape the double-quote character in the second element:

# result from ExampleHandler
<something >
  <b name="FOO">blargh</b>
  <b name="FOO"BAR">baz</b>
  <z nothing="nope"></z>
</something>

(it also adds stray blanks to the end of tags like something and swaps z to the other format, but IIRC both of those aren’t semantic changes)

zachallaun

zachallaun

You can use something like XmlBuilder as well. Here’s how it handles escaping.

Edit: also relevant StackOverflow about XML escaping requirements.

czrpb

czrpb OP

thx everyone and awesome community!

:grin:

barrier436

barrier436

I’m trying to do something similar, I was wondering what your final solution for this problem looks like?

— All posts loaded —

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews