@@ -14,6 +14,64 @@ parsing XML via the built in `xmerl` library in Erlang.
14
14
15
15
[ Here is the project built in this episode, for you to download.] ( http://elixirsips.com/downloads/028_parsing_xml.tar.gz )
16
16
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
+
17
75
## Resources
18
76
- [ xmerl user guide] ( http://www.erlang.org/doc/apps/xmerl/xmerl_ug.html )
19
77
- [ xmerl manual] ( http://www.erlang.org/doc/man/xmerl_scan.html )
0 commit comments