Reputation: 15746
So let's say I have an XML file and I want to remove some nodes from it using their XPath. How would I do that and is it possible in the first place with xmerl
or erlsom
or maybe something else?
And if there is not a simple way with XPath, what is the correct way to remove elements from XML in general?
Upvotes: 2
Views: 774
Reputation: 121010
As stated by W3C,
XPath is a language for addressing parts of an XML document
the above literally means XPath
is to query XML, not to modify it. The common approach to modifying XML document, would be to one of those:
AFAIU, the former is out of the scope of this question. For the latter, one might use Exsom
library, which is “an Elixir wrapper around the erlsom
XML parsing library.”
Assuming we have the xml
and xsd
taken from Excom
examples:
<?xml version="1.0" encoding="UTF-8"?>
<foo attr="yo">
<bar>1</bar>
<bar>2</bar>
</foo>
One might do something like this to delete second bar
node (most of the code is taken as is from Excom
tests:
{ :ok, model } = Exsom.XSD.File.parse("complex.xsd")
{ :ok, instance, _ } = Exsom.File.parse("complex.xml", model)
#⇒ {:ok, {:foo_type, [], 'yo', ['1', '2']}}
Modify it according to what you want, e.g. remove bar
element with 2
instance = {:foo_type, [], 'yo', ['1']}
{ :ok, binary_xml } = Exsom.compose(instance, model, [{ :output, :binary }])
#⇒ {:ok, "<foo attr=\"yo\"><bar>1</bar></foo>"}
Now you might write the binary_xml
to a file.
Upvotes: 2