odeac

odeac

How to parse sub-element list with SweetXml?

I have to parse an XML with the following structure:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

    <root >
        <node id="1"/>
        <node id="2"/>
    </root>

And I have tried the following approache based on xpath:


  def parse_root(root_xml) do
    root_xml
    |> xpath(~x"//root",
      nodes: ~x"./node"l |> transform_by(&parse_node/1)
    )
  end

  def parse_node(node_xml) do
    node_xml
    |> xpath(~x"node", id: ~x"@id")
  end

  test "parse root" do
    xml = """
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>

    <root >
        <node id="1"/>
        <node id="2"/>
    </root>
    """

    assert %{
             nodes: [
               %{id: "id1"},
               %{id: "id2"}
             ]
           } == parse_root(xml)
  end

This fails with the following runtime error:

  2) test parse root (TestSweet)
     test/sweet_test.exs:172
     ** (ArgumentError) errors were found at the given arguments:

       * 1st argument: not a bitstring

     code: } == parse_root(xml)
     stacktrace:
       :erlang.byte_size({:xmlElement, :node, :node, [], {:xmlNamespace, [], []}, [root: 1], 2, [{:xmlAttribute, :id, [], [], [], [node: 2, root: 1], 1, [], ~c"1", false}], [], [], ~c"/Users/ovi/work/eb/playground", :undeclared})
       (sweet_xml 0.7.4) lib/sweet_xml.ex:834: SweetXml.split_last_whitespace/1
       (sweet_xml 0.7.4) lib/sweet_xml.ex:825: anonymous fn/2 in SweetXml.split_by_whitespace/1
       (elixir 1.15.7) lib/stream.ex:990: Stream.do_transform_user/6
       (sweet_xml 0.7.4) lib/sweet_xml.ex:788: anonymous fn/4 in SweetXml.continuation_opts/2
       (xmerl 1.3.31) xmerl_scan.erl:571: :xmerl_scan.scan_document/2
       (xmerl 1.3.31) xmerl_scan.erl:294: :xmerl_scan.string/2
       (sweet_xml 0.7.4) lib/sweet_xml.ex:296: SweetXml.do_parse/2
       (sweet_xml 0.7.4) lib/sweet_xml.ex:281: SweetXml.parse/2
       (sweet_xml 0.7.4) lib/sweet_xml.ex:610: SweetXml.xpath/3
       (sweet_xml 0.7.4) lib/sweet_xml.ex:642: SweetXml.xpath/3
       (sweet_xml 0.7.4) lib/sweet_xml.ex:737: anonymous fn/3 in SweetXml.xmap/3
       (elixir 1.15.7) lib/map.ex:957: Map.get_and_update/3
       (sweet_xml 0.7.4) lib/sweet_xml.ex:737: SweetXml.xmap/3
       test/sweet_test.exs:187: (test)

I also tried to parse the same XML using xmap as you can see below:

def parse_root2(root_xml) do
    root_xml
    |> xmap(~x"//root",
      nodes: [
        ~x"./node",
        id: ~x"@id"
      ]
    )
  end

  test "parse root 2" do
    xml = """
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>

    <root >
        <node id="1"/>
        <node id="2"/>
    </root>
    """

    assert %{
             nodes: [
               %{id: "id1"},
               %{id: "id2"}
             ]
           } == parse_root2(xml)
  end

…and it fails with the following error:

  1) test parse root 2 (TestSweet)
     test/sweet_test.exs:200
     ** (FunctionClauseError) no function clause matching in SweetXml.xmap/3

     The following arguments were given to SweetXml.xmap/3:

         # 1
         "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n\n<root >\n    <node id=\"1\"/>\n    <node id=\"2\"/>\n</root>\n"

         # 2
         %SweetXpath{path: ~c"//root", is_value: true, is_list: false, is_keyword: false, is_optional: false, cast_to: false, transform_fun: &SweetXpath.Priv.self_val/1, namespaces: []}

         # 3
         [nodes: [%SweetXpath{path: ~c"./node", is_value: true, is_list: false, is_keyword: false, is_optional: false, cast_to: false, transform_fun: &SweetXpath.Priv.self_val/1, namespaces: []}, {:id, %SweetXpath{path: ~c"@id", is_value: true, is_list: false, is_keyword: false, is_optional: false, cast_to: false, transform_fun: &SweetXpath.Priv.self_val/1, namespaces: []}}]]

     Attempted function clauses (showing 6 out of 6):

         def xmap(nil, _, %{is_optional: true})
         def xmap(parent, [], atom) when is_atom(atom)
         def xmap(_, [], %{is_keyword: false})
         def xmap(_, [], %{is_keyword: true})
         def xmap(parent, [{label, spec} | tail], is_keyword) when is_list(spec)
         def xmap(parent, [{label, sweet_xpath} | tail], is_keyword)

     code: } == parse_root2(xml)
     stacktrace:
       (sweet_xml 0.7.4) lib/sweet_xml.ex:721: SweetXml.xmap/3
       test/sweet_test.exs:215: (test)

Any suggestions will be highly appreciated.

Thanks in advance!

Marked As Solved

Hermanverschooten

Hermanverschooten

I tried this in a livebook.

import SweetXml
xml = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

    <root >
        <node id="1"/>
        <node id="2"/>
    </root>
"""

xml
|> xpath(~x"//root", nodes: [~x"./node"l, id: ~x"@id"i])

%{nodes: [%{id: 1}, %{id: 2}]}

xml
|> xpath(~x"//root", nodes: [~x"./node"l, id: ~x"@id"s |> transform_by(fn x -> "id" <> x end)])

%{nodes: [%{id: "id1"}, %{id: "id2"}]}

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; somethi...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New

Other popular topics Top

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New

We're in Beta

About us Mission Statement