SweetXml.xpath
xpath
, go back to SweetXml module for more information.
Specs
xpath(parent :: doc() | xmlElement(), spec(), subspec) :: any() when subspec: keyword(spec() | subspec)
xpath
allows you to query an XML document with XPath.
The second argument to xpath is a %SweetXpath{}
struct. The optional third
argument is a keyword list, such that the value of each keyword is also
either a %SweetXpath{}
or a list with head being a %SweetXpath{}
and tail being
another keyword list exactly like before. Please see the examples below for better
understanding.
Examples
Simple:
iex> import SweetXml
iex> doc = "<h1><a>Some linked title</a></h1>"
iex> doc |> xpath(~x"//a/text()")
'Some linked title'
With optional mapping:
iex> import SweetXml
iex> doc = "<body><header><p>Message</p><ul><li>One</li><li><a>Two</a></li></ul></header></body>"
iex> doc |> xpath(~x"//header", message: ~x"./p/text()", a_in_li: ~x".//li/a/text()"l)
%{a_in_li: ['Two'], message: 'Message'}
With optional mapping and nesting:
iex> import SweetXml
iex> doc = "<body><header><p>Message</p><ul><li>One</li><li><a>Two</a></li></ul></header></body>"
iex> doc
...> |> xpath(
...> ~x"//header",
...> ul: [
...> ~x"./ul",
...> a: ~x"./li/a/text()"
...> ]
...> )
%{ul: %{a: 'Two'}}
Security
Whenever you are working with some xml that was not generated by your system, it is highly recommended that you restrain some functionalities of XML during the parsing. SweetXml allows in particular to prevent DTD parsing and fetching. Unless you know exactly what kind of DTD you want to permit in your xml, it is recommended that you use the following code example to prevent possible attacks:
doc
|> parse(dtd: :none)
|> xpath(spec, subspec)
For more details, see parse/2
.