Skip to content

Instantly share code, notes, and snippets.

@developerworks
Last active July 4, 2016 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save developerworks/94ce9976fc52e04e572a to your computer and use it in GitHub Desktop.
Save developerworks/94ce9976fc52e04e572a to your computer and use it in GitHub Desktop.
在Elixir中解析XML文档
defmodule XmlParsingTest do
@moduledoc """
从xmerl模块头文件中提取XML元素记录
我们要提取的两个记录在xmerl.hrl中的定义分别为
- xmlElement
```
-record(xmlElement,{
name, % atom()
expanded_name = [], % string() | {URI,Local} | {"xmlns",Local}
nsinfo = [], % {Prefix, Local} | []
namespace=#xmlNamespace{},
parents = [], % [{atom(),integer()}]
pos, % integer()
attributes = [], % [#xmlAttribute()]
content = [],
language = "", % string()
xmlbase="", % string() XML Base path, for relative URI:s
elementdef=undeclared % atom(), one of [undeclared | prolog | external | element]
}).
```
- xmlText
```
-record(xmlText,{
parents = [], % [{atom(),integer()}]
pos, % integer()
language = [],% inherits the element's language
value, % IOlist()
type = text % atom() one of (text|cdata)
}).
```
"""
use ExUnit.Case
require Record
Record.defrecord :xmlElement, Record.extract(:xmlElement, from_lib: "xmerl/include/xmerl.hrl")
Record.defrecord :xmlText, Record.extract(:xmlText, from_lib: "xmerl/include/xmerl.hrl")
def sample_xml do
"""
<blog>
<title>Using xmerl module to parse xml document in elixir</title>
</blog>
"""
end
test "Test parsing xml document" do
{document, _} = :xmerl_scan.string(String.to_char_list(sample_xml))
[element] = :xmerl_xpath.string('/blog/title/text()', document)
assert xmlText(element, :value) == 'Using xmerl module to parse xml document in elixir'
end
end
@fireyang
Copy link

fireyang commented Jul 4, 2016

:binary.bin_to_list 替代 String.to_char_list ,否则中文报错

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment