系列之十八:如何应用XSL和正则表达式来验证数据的有效性(二) 现在持续我在上一系列中先容的例子。我们将实现一个简略的搜索机制, 也许你的爱好不是在获取书籍的标题而是在要获得全部书节点(note)上。 那么应用下面这个函数就能够满足你的请求了 Public Function GetFilteredElements(activeElement As Variant, RegExpfilter As String, _ Optional queryString As String = '',optional IsGlobal as Boolean=True, _ optional IgnoreCase as Boolean = True) As IXMLDOMNodeList Dim re As RegExp Dim filterDoc As DOMDocument Dim nodelist As IXMLDOMNodeList Dim filterList As IXMLDOMNodeList Dim node As IXMLDOMElement Dim baseNode As IXMLDOMElement Set re = New RegExp On Error GoTo ErrorHandler Select Case TypeName(activeElement) Case 'IXMLDOMElement' Set baseNode = activeElement Case 'DOMDocument' Set baseNode = activeElement.documentElement Case Else Error 1001 Set GetFilteredElements = Nothing End Select re.Pattern = RegExpfilter re.Global=IsGlobal re.IgnoreCase=IgnoreCase If queryString = '' Then Set filterList = baseNode.selectNodes('.[textnode()]|.//*[textnode()]') Else Set filterList = baseNode.selectNodes(queryString) End If For Each node In filterList If re.Test(node.Text) Then node.setAttribute 'filter:filteredElementFound', 'true' End If Next Set filterList = baseNode.selectNodes('.[@filter:filteredElementFound]|.//*[@filter:filteredElementFound]') For Each node In filterList node.removeAttribute 'filter:filteredElementFound' Next Set GetFilteredElements = filterList Exit Function ErrorHandler: If Err.Number = 1001 Then MsgBox 'Document must be an XML document, or a document element.' Else Error Err.Number End If End Function
当然,你也可以转变你的XSL中的查询参数(例如上面例子中应用的参数是xml) 一个直接的方法是天生一个参数实体'entities' 例如下面的代码,你需要应用'%'字符来阐明一个字符是参数。 Function SetXSLParameter(XslDoc as DOMDocument ,ParamName as _ String,ParamValue as Variant) as DOMDocument Dim XslDoc as DOMDocument Dim ScriptNode as IXMLDOMElement Dim re as RegExp
Set re=new RegExp Re.global=True Re.IgnoreCase=True Re.pattern='%' ParamName For each ScriptNode in xslDoc.selectNodes('xsl:script') ScriptNode.text=Re.replace(ScriptNode.text,cstr(ParamValue)) Next Return XslDoc End Function