Last active
July 4, 2016 17:55
-
-
Save developerworks/94ce9976fc52e04e572a to your computer and use it in GitHub Desktop.
在Elixir中解析XML文档
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
:binary.bin_to_list 替代 String.to_char_list ,否则中文报错