edasssus
edasssus

Reputation: 351

Keep elements in text with XPath

I have a XML files, and each file contains some informations, it also contains description of itself closed in element <namespace:description></namespace:description>. This description will be inserted in HTML web page and uploaded to web.

The problem is that in description element are other HTML elements and I want to keep them there, so that text can be formatted, but XPath escape all those elements and returns only their text.

<namespace:descr>Some <i>nice</i> description</namespace:descr>

I tried variations on this XPath query: //*[local-name()='descr'] (I'm not really skilled with XPath)

Also tried something like //*[local-name()='descr']//*[not(descendant::*[self::p or self::i])] found in this answer, but it doesn't work for me.

So my question: is there some way to keep XML/HTML elements in text after using XPath query?

Upvotes: 0

Views: 768

Answers (1)

wero
wero

Reputation: 33010

The return value of an XPath expression can either be a string, number, boolean or a node-set. Each of these types can be converted to one of the primitive types.

The expression //*[local-name()='descr'] returns a node-set but you then obviously convert it to a string which returns the concatenated text content of the first node in the node-set, stripping off all markup.

To print the content of the result node as markup you would need to do the following:

  1. Retrieve the expression result as node-set. The implementation type of the node-set depends on the XPath engine, and for instance could be a DOM nodelist.
  2. Serialize the nodes as XML fragment. This of course depends on the API node-set and the XPath engine. XSLT could be used for that but it may also be as simple as calling toString() on the node implementation.

Upvotes: 3

Related Questions