Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an XML node contains text

Tags:

xml

xslt

xslt-2.0

How can I check if a XML node contains text, or only empty nodes?

Example: Let's say we have the following XML:

<text>
   <p> </p>
   <p> </p>
</text>

(Note the whitespace between the p tags)

In a different XML, we have the following XML:

<text>
   <p>Hello World!</p>
</text>

I'd like the test to pass in the second example, but not in the first, as the second example contains text, but the first contains empty nodes.

Is there a way to easily achieve this?

(I use XSLT 2.0.)

like image 517
Helge Avatar asked Aug 30 '12 07:08

Helge


People also ask

How do I check if a node exists in XML?

To verify if node or tag exists in XML content, you can execute an xpath expression against DOM document for that XML and count the matching nodes. matching nodes > zero – XML tag / attribute exists.

What is text node in XML?

A text node encapsulates XML character content. A text node can have zero or one parent. The content of a text node can be empty. However, unless the parent of a text node is empty, the content of the text node cannot be an empty string.

How do you check if XML document is blank or has values?

You can try to load the XML into XML document and catch the exception. Here is the sample code: var doc = new XmlDocument(); try { doc. LoadXml(content); } catch (XmlException e) { // put code here that should be executed when the XML is not valid. }

What is the difference between XmlNode and XmlElement?

Every XmlElement is XmlNode, but not every XmlNode is XmlElement. XmlElement is just one kind of XmlNode. Others are XmlAttribute, XmlText etc. An Element is part of the formal definition of a well-formed XML document, whereas a node is defined as part of the Document Object Model for processing XML documents.


2 Answers

I think normalize-space does what you want, e.g. this will 'pass':

<xsl:if test="normalize-space(/text/p) != ''">
    ...
</xsl:if>

normalize-space will trim all leading and trailing whitespace from a string, which will leave text behind in your second example, but remove all characters in your first example allowing you to compare against the empty string ''.

Note it also compresses multiple whitespace characters in sequence into a single character, so for example hello<space><space><space>there would become hello<space>there.

http://www.w3.org/TR/xpath/#function-normalize-space (XPath 1)

like image 67
actionshrimp Avatar answered Oct 19 '22 14:10

actionshrimp


Use:

p[normalize-space()]

This selects any p child of the context (current) node, whose string-value is not the empty string or a whitespace-only string.

like image 27
Dimitre Novatchev Avatar answered Oct 19 '22 13:10

Dimitre Novatchev