我正在尝试模式匹配这些值,这些值通过运行mochixpath返回。模式显然是elemName、htmlAttrs、子模式,但我真正需要的是UserNameA和“这是一条消息”
[{"tr", [{"bgcolor", "White"}],
[{"td", [{"class", "Topic"}],
[{"div", [],
[{"a", [{"class", "lnkUserName"}, {"href", "/users/prof.aspx?u=27149"}],
["UserNameA"]
}]
}]},
{"img", [{"alt", ""}, {"src", "/Images/Icons/userIcon.gif"}], []},
{"td", [{"class", "bHeader"}],
[{"div", [{"style", "float:left;width:77%;"}],[
{"a", [{"class", "PostDisplay"}],
["This is a message"]}]
}]
}]
实际上,我使用xpath输出中的解析xml来获取用户名和它们发送的消息。我是非常新的灵丹妙药和模式匹配的概念,所以任何帮助都是非常感谢的。
发布于 2014-10-15 23:39:03
在你的例子中,卷曲和方括号是不平衡的。我想它在结尾缺少了一个}]
。
似乎表达式的深度可能会有所不同,所以您必须递归地探索它。假设您将在"a“元素中找到信息,下面的代码会这样做:
-module (ext).
-compile([export_all]).
extL(L) -> extL(L,[]).
extL([],R) -> R;
extL([H|Q],R) -> extL(Q, extT(H) ++ R).
extT({"a",PropL,L}) ->
case proplists:get_value("class",PropL) of
"lnkUserName" -> [{user_name, hd(L)}];
"PostDisplay" -> [{post_display,hd(L)}];
_ -> extL(L,[])
end;
extT({_,_,L}) -> extL(L,[]).
对于您的示例,它返回proplist [{post_display,"This is a message"},{user_name,"UserNameA"}]
发布于 2014-10-15 23:20:53
当我将输出复制到控制台时,输出出现了一些问题,因为它产生了语法错误,所以我假设您有tr,其中包含td、img和其他td。
模式匹配可用于这种方式的展开。让我们说,您的整个数据都在变量Data
中,您可以使用以下方法提取内容:
[TR] = Data,
{_Name, _Attrs, Contents} = TR.
现在,内容又是一个节点列表:[Td1, Img, Td2]
,所以您可以:
[Td1, Img, Td2] = Contents.
以此类推,直到你真正达到你的内容。但是写起来很乏味,你可以用递归代替。让我们定义contents
函数,它递归地扫描元素。
contents({_Name, _Attrs, Contents}) ->
case Contents of
[] -> []; % no contents like in img tag
[H | T] ->
case is_tuple(H) of
% tupe means list of children
true -> lists:map(fun contents/1, [H | T]);
% otherwise this must be a string
_ -> [H | T]
end
end.
这将返回嵌套列表,但最终可以像这样运行lists:flatten
:
Values = lists:flatten(contents(Data)).
https://stackoverflow.com/questions/26396198
复制相似问题