Sets the inner text in a node. If the node doesn't exist, it creates a new one and adds the text to it. : DOM « XML « C# / C Sharp






Sets the inner text in a node. If the node doesn't exist, it creates a new one and adds the text to it.

        


using System;
using System.Xml;

namespace Microsoft.SnippetLibrary
{
    /// <summary>
    /// Summary description for Util.
    /// </summary>
    public class Utility
    {

        /// <summary>
        /// Sets the inner text in a node.  If the node doesn't
        /// exist, it creates a new one and adds the text to it.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="name">The name.</param>
        /// <param name="text">The text.</param>
        /// <param name="nsMgr">The ns MGR.</param>
        /// <returns></returns>
        public static XmlNode SetTextInDescendantElement(XmlElement element, string name, string text, XmlNamespaceManager nsMgr)
        {
            return SetTextInElement(element,name,text,nsMgr,false);
        }

        public static XmlNode SetTextInChildElement(XmlElement element, string name, string text, XmlNamespaceManager nsMgr)
        {
            return SetTextInElement(element, name, text, nsMgr, true);
        }


        private static XmlNode SetTextInElement(XmlElement element, string name, string text, XmlNamespaceManager nsMgr, bool isChild)
        {
            if (element == null)
                throw new Exception("Passed in a null node, which should never happen.");

            var selector = "descendant";
            if (isChild)
                selector = "child";

            XmlElement newElement = (XmlElement)element.SelectSingleNode(selector + "::ns1:" + name, nsMgr);

            if (newElement == null)
            {
                newElement = (XmlElement)element.AppendChild(element.OwnerDocument.CreateElement(name, nsMgr.LookupNamespace("ns1")));
            }

            newElement.InnerText = text;
            return element.AppendChild(newElement);
        }

    }
}

   
    
    
    
    
    
    
    
  








Related examples in the same category

1.DOM feature check
2.Create Xml Document, Node
3.Load String from xml element
4.Load boolean value from xml element
5.Get integer value from xml element
6.Get attribute from XmlNode
7.Set Xml Node Value
8.Get Value String from Xml
9.Get InnerXml without changing the spacing
10.Get Inner Xml
11.Add Xml Element
12.Returns the InnerText value from a node or string.Empty if the node is null.