Skip to content

Commit d23cc15

Browse files
Josh AdamsJosé Valim
Josh Adams
authored and
José Valim
committed
Add some code to the xml post, so it's not just a video embed
Signed-off-by: José Valim <[email protected]>
1 parent f95e179 commit d23cc15

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

_posts/2013-12-27-parsing-xml-with-elixir.markdown

+58
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,64 @@ parsing XML via the built in `xmerl` library in Erlang.
1414

1515
[Here is the project built in this episode, for you to download.](http://elixirsips.com/downloads/028_parsing_xml.tar.gz)
1616

17+
You can watch the video for a complete rundown where we use tests to explore the
18+
`xmerl` library and how we can use it from Elixir. If you just want to see the
19+
results, here's the test file we ended up with, commented for clarity:
20+
21+
```elixir
22+
# If you want to pattern-match on a record defined in an erlang library, you
23+
# need to use Record.extract to turn it into an Elixir record data structure.
24+
# Here, we extract xmlElement and xmlText from xmerl.
25+
defrecord :xmlElement, Record.extract(:xmlElement, from_lib: "xmerl/include/xmerl.hrl")
26+
defrecord :xmlText, Record.extract(:xmlText, from_lib: "xmerl/include/xmerl.hrl")
27+
28+
defmodule XmlParsingTest do
29+
use ExUnit.Case
30+
31+
# Here we define some simple XML that we'll work with in our tests.
32+
def sample_xml do
33+
"""
34+
<html>
35+
<head>
36+
<title>XML Parsing</title>
37+
</head>
38+
<body>
39+
<p>Neato</p>
40+
<ul>
41+
<li>First</li>
42+
<li>Second</li>
43+
</ul>
44+
</body>
45+
</html>
46+
"""
47+
end
48+
49+
test "parsing the title out" do
50+
{ xml, _rest } = :xmerl_scan.string(bitstring_to_list(sample_xml))
51+
[ title_element ] = :xmerl_xpath.string('/html/head/title', xml)
52+
[ title_text ] = title_element.content
53+
title = title_text.value
54+
55+
assert title == 'XML Parsing'
56+
end
57+
58+
test "parsing the p tag" do
59+
{ xml, _rest } = :xmerl_scan.string(bitstring_to_list(sample_xml))
60+
[ p_text ] = :xmerl_xpath.string('/html/body/p/text()', xml)
61+
62+
assert p_text.value == 'Neato'
63+
end
64+
65+
test "parsing the li tags and mapping them" do
66+
{ xml, _rest } = :xmerl_scan.string(bitstring_to_list(sample_xml))
67+
li_texts = :xmerl_xpath.string('/html/body/ul/li/text()', xml)
68+
texts = li_texts |> Enum.map(fn(x) -> x.value end)
69+
70+
assert texts == ['First', 'Second']
71+
end
72+
end
73+
```
74+
1775
## Resources
1876
- [xmerl user guide](http://www.erlang.org/doc/apps/xmerl/xmerl_ug.html)
1977
- [xmerl manual](http://www.erlang.org/doc/man/xmerl_scan.html)

0 commit comments

Comments
 (0)