让我们开始确保您的 XmlDocument 正在从您的内容块控件引用 smartform xml。
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(alert.EkItem.Html);
除此之外,我将通过以下方式进行测试以验证 (a) 节点是否存在以及 (b) 节点是否包含文本。
string alertContent;
// If dealing with a plain-text field...
var txtAlertNode = xmlDoc.SelectSingleNode("/root/txtAlert");
alertContent = txtAlertNode?.InnerText;
if (string.IsNullOrWhiteSpace(alertContent))
{
Console.WriteLine("No txtAlert content.");
// alertBox.Visible = false;
}
else
{
Console.WriteLine("ALERT: " + alertContent);
// alertBox.Visible = true;
}
// If dealing with a rich-text field...
var rtfAlertNode = xmlDoc.SelectSingleNode("/root/rtfAlert");
if (string.IsNullOrWhiteSpace(rtfAlertNode?.InnerText))
{
Console.WriteLine("No rtfAlert content.");
// alertBox.Visible = false;
}
else
{
alertContent = rtfAlertNode.InnerXml;
Console.WriteLine("ALERT: " + alertContent);
// alertBox.Visible = true;
}
但由于您拥有呈现实际警报内容的内容块控件,因此您可以避免这样的事情。
var alertNode = xmlDoc.SelectSingleNode("/root/Alert");
if (string.IsNullOrWhiteSpace(alertNode?.InnerText))
{
alertBox.Visible = false;
}
else
{
alertBox.Visible = true;
}
在 Ektron SmartForms 中,可以选择将字段设为可选,因此/root/Alert 节点可能为空。但也有可能该节点将存在于 xml 中并且简单地没有任何内容。如果将其配置为富文本字段,则可能很难完全清除该字段的 HTML - 通常您最终会得到如下所示的 xml:
<root>
<Alert>
<p></p>
</Alert>
</root>
这就是我测试节点的InnerText 属性的原因。我使用Null-Conditional Operator ?. 来说明节点本身可能为空的事实。如果您的 Ektron 站点没有使用较新的 C# 语言功能(我知道,null 条件已经存在几年了。),那么您必须单独检查 null。
var alertNode = xmlDoc.SelectSingleNode("/root/Alert");
if (alertNode != null && string.IsNullOrWhiteSpace(alertNode.InnerText))
{
alertBox.Visible = false;
}
else
{
alertBox.Visible = true;
}
如果可以的话,我想提出一个替代方案。我从您的代码中看到您已经在使用 XSLT 来显示警报的内容。您可以将alertBox div 的标记移动到您的XSLT 中并在那里执行“null-or-empty”测试。那么你就不需要任何代码隐藏来实现这个特定的功能了。
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
<xsl:output method="html" indent="yes"/>
<xsl:template match="/">
<xsl:call-template name="alertBox">
<xsl:with-param name="content" select="root/txtAlert/text()"/>
</xsl:call-template>
<xsl:call-template name="alertBox">
<xsl:with-param name="content" select="root/rtfAlert/node()"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="alertBox">
<xsl:param name="content"/>
<xsl:if test="$content and (string-length(translate(normalize-space($content/text()), ' ', '')) > 0 or string-length(translate(normalize-space($content), ' ', '')) > 0)">
<div runat="server" ID="alertBox" class="alert alert-danger">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<center>
<xsl:copy-of select="$content"/>
</center>
</div>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
请注意,此 XSLT 中的 alertBox 模板适用于纯文本和富文本字段。它使用copy-of 来显示传入的任何内容,因此在调用模板时,需要注意传入text()(纯文本)或node()(html/富文本)元素根据其类型。