Project

Profile

Help

Remove attribute from element using Java API?

Added by Aleksandar M about 7 years ago

Hello,

I'm trying to learn the proper way to use the Saxon Java API (Saxon HE 9.8).

Thanks to the documentation I'm able to read an XML file using @Processor@, @DocumentBuilder@ etc.

After selecting some nodes using a @XPathSelector@ I would like to remove some attributes from those nodes before processing them further.

For example I would like to remove @attr1@ from this element:



Is the Java API suited for these kind of manipulations, and if so what class/methods do you recommend? Or do I have to make a call to XSLT?

Thanks!


Replies (2)

RE: Remove attribute from element using Java API? - Added by Michael Kay about 7 years ago

Most of the implementations of the XdmNode interface (which an XPathSelector returns), and of the underlying NodeInfo interface, are immutable: the Saxon tree model is designed primarily for use by XQuery, XSLT, and XPath. There are some mutable implementations (nodes in the linked tree model implement MutableNodeInfo) but the APIs for modifying a tree are designed very specifically with the needs of XQuery Update in mind, rather than for general-purpose Java programming.

If you really want to go down this route I would recommend building the tree using XOM or JDOM2 (or DOM if you must -- but beware of thread safety). The nodes returned by a Saxon XPath query will then be XOM or JDOM2 nodes, which you can modify using the XOM or JDOM2 API.

RE: Remove attribute from element using Java API? - Added by Aleksandar M about 7 years ago

Thanks Michael, that clears things up for me.

I decided to go with a XSLT file approach, it turned out to be much easier than I thought.

I let the stylesheet preprocess the file and set the destination to @XdmDestination@.

    (1-2/2)

    Please register to reply