Inserting Nodes into a Message from the BRE
One of the problems I’ve always had with the Business Rules Engine (BRE) is that there is no built-in vocabulary or functionality that allows one to add nodes to an XML Document. Below I present one possible way to accomplish this.
Since the BRE doesn’t contain this capability natively, you have to rely on good ol’ .NET code to get the job done. For this, I’ve used basic DOM capabilities to do a node insertion–nothing fancy at all.
First, we have to work with the BRE’s own version of the XmlDocument called a TypedXmlDocument. The TypedXmlDocument is similar to the DOM version except, among other things, it carries a textual key which allows the BRE to identify it within a fact list. In the code below, we accept one of these as the parameter of our static method. The other parameters are strings which contain the xPath to the parent node, the name of the node we want to add, its value, and the namespace to use. Here’s the code:
public static void AddNodeWithValue(TypedXmlDocument txd,
string parentNodeXPath, string nodeName,
string nodeValue, string nodeNamespace)
{
XmlNode node = null;
XmlNode parent = txd.Document;
node = parent.SelectSingleNode( xPath, txd.NamespaceManager );
XmlDocument root = node.OwnerDocument;
if (null == root)
{
root = txd.Document as XmlDocument;
if (null == root)
{
return;
}
}
// create a new node and add it in
XmlElement newNode;
if (nodeNamespace != null)
{
string prefix = node.GetPrefixOfNamespace(nodeNamespace);
if (prefix == null || prefix == string.Empty)
newNode = root.CreateElement(nodeName, nodeNamespace);
else
newNode = root.CreateElement(prefix, nodeName, nodeNamespace);
}
else
{
newNode = root.CreateElement(nodeName);
}
newNode.InnerText = nodeValue;
node.InsertBefore(newNode, null);
}
Nothing fancy here, just simple DOM activity. Once you’ve built this code into a component, you can use it in a rule by adding it as a fact in the Business Rules Composer.