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.)
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.
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.
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. }
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With