SecurityElement Class


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

Represents the XML object model for encoding security objects. This class cannot be inherited.

Namespace:   System.Security
Assembly:  mscorlib (in mscorlib.dll)


public sealed class SecurityElement


Initializes a new instance of the SecurityElement class with the specified tag.

System_CAPS_pubmethodSecurityElement(String, String)

Initializes a new instance of the SecurityElement class with the specified tag and text.


Gets or sets the attributes of an XML element as name/value pairs.


Gets or sets the array of child elements of the XML element.


Gets or sets the tag name of an XML element.


Gets or sets the text within an XML element.

System_CAPS_pubmethodAddAttribute(String, String)

Adds a name/value attribute to an XML element.


Adds a child element to the XML element.


Finds an attribute by name in an XML element.


Creates and returns an identical copy of the current SecurityElement object.


Compares two XML element objects for equality.


Determines whether the specified object is equal to the current object.(Inherited from Object.)


Replaces invalid XML characters in a string with their valid XML equivalent.


Creates a security element from an XML-encoded string.


Serves as the default hash function. (Inherited from Object.)


Gets the Type of the current instance.(Inherited from Object.)


Determines whether a string is a valid attribute name.


Determines whether a string is a valid attribute value.


Determines whether a string is a valid tag.


Determines whether a string is valid as text within an XML element.


Finds a child by its tag name.


Finds a child by its tag name and returns the contained text.


Produces a string representation of an XML element and its constituent attributes, child elements, and text.(Overrides Object.ToString().)

This class is intended to be a lightweight implementation of a simple XML object model for use within the security system, and not for use as a general XML object model. This documentation assumes a basic knowledge of XML.

The simple XML object model for an element consists of the following parts:

  • The tag is the element name.

  • The attributes are zero or more name/value attribute pairs on the element.

  • The children are zero or more elements nested within <tag> and </tag>.

It is strongly suggested that attribute based XML representation is used to express security elements and their values. This means properties of an element are expressed as attributes and property values are expressed as attribute values. Avoid nesting text within tags. For any <tag>text</tag> representation a representation of type <tag value="text"/> is usually available. Using this attribute-based XML representation increases readability and allows easy WMI portability of the resulting XML serialization.

An attribute name must be one character or longer, and cannot be null. If element-based value representation is used, elements with a text string that is null are represented in the <tag/> form; otherwise, text is delimited by the <tag> and </tag> tokens. Both forms can be combined with attributes, which are shown if present.

The tags, attributes, and text of elements, if present, are always case-sensitive. The XML form contains quotations and escapes where necessary. String values that include characters invalid for use in XML result in an ArgumentException. These rules apply to all properties and methods.


For performance reasons, character validity is only checked when the element is encoded into XML text form, and not on every set of a property or method. Static methods allow explicit checking where needed.

The following example shows the use of members of the SecurityElement class.

using System;
using System.Security;
using System.Collections;

class SecurityElementMembers
    static void Main(string[] args)
        SecurityElement xmlRootElement = 
            new SecurityElement("RootTag", "XML security tree");


        SecurityElement windowsRoleElement = 
            new SecurityElement("WindowsMembership.WindowsRole");


        // Add a child element and a creationdate attribute.
            "This is a child element");


        CompareAttributes(xmlRootElement, "creationdate");


        // Determine if the security element is too old to keep.
        xmlRootElement = DestroyTree(xmlRootElement);
        if (xmlRootElement != null)
            string elementInXml = xmlRootElement.ToString();

        Console.WriteLine("This sample completed successfully; " +
            "press Enter to exit.");

    // Add an attribute to the specified security element.
    private static SecurityElement AddAttribute(
        SecurityElement xmlElement,
        string attributeName,
        string attributeValue)
        if (xmlElement != null)
            // Verify that the attribute name and value are valid XML formats.
            if (SecurityElement.IsValidAttributeName(attributeName) &&
                // Add the attribute to the security element.
                xmlElement.AddAttribute(attributeName, attributeValue);
        return xmlElement;

    // Add a child element to the specified security element.
    private static SecurityElement AddChildElement(
        SecurityElement parentElement,
        string tagName,
        string tagText)
        if (parentElement != null)
            // Ensure that the tag text is in valid XML format.
            if (!SecurityElement.IsValidText(tagText))
                // Replace invalid text with valid XML text 
                // to enforce proper XML formatting.
                tagText = SecurityElement.Escape(tagText);

            // Determine whether the tag is in valid XML format.
            if (SecurityElement.IsValidTag(tagName))
                SecurityElement childElement;
                childElement = parentElement.SearchForChildByTag(tagName);

                if (childElement != null)
                    String elementText;
                    elementText = parentElement.SearchForTextOfTag(tagName);

                    if (!elementText.Equals(tagText))
                        // Add child element to the parent security element.
                            new SecurityElement(tagName, tagText));
                    // Add child element to the parent security element.
                        new SecurityElement(tagName, tagText));
        return parentElement;

    // Create and display a summary sentence 
    // about the specified security element.
    private static void DisplaySummary(SecurityElement xmlElement)
        // Retrieve tag name for the security element.
        string xmlTreeName = xmlElement.Tag.ToString();

        // Retrieve tag text for the security element.
        string xmlTreeDescription = xmlElement.Text;

        // Retrieve value of the creationdate attribute.
        string xmlCreationDate = xmlElement.Attribute("creationdate");

        // Retrieve the number of children under the security element.
        string childrenCount = xmlElement.Children.Count.ToString();

        string outputMessage = "The security XML tree named " + xmlTreeName;
        outputMessage += "(" + xmlTreeDescription + ")";
        outputMessage += " was created on " + xmlCreationDate + " and ";
        outputMessage += "contains " + childrenCount + " child elements.";


    // Compare the first two occurrences of an attribute 
    // in the specified security element.
    private static void CompareAttributes(
        SecurityElement xmlElement, string attributeName)
        // Create a hash table containing the security element's attributes.
        Hashtable attributeKeys = xmlElement.Attributes;
        string attributeValue = attributeKeys[attributeName].ToString();

        foreach(SecurityElement xmlChild in xmlElement.Children)
            if (attributeValue.Equals(xmlChild.Attribute(attributeName)))
                // The security elements were created at the exact same time.

    // Convert the contents of the specified security element 
    // to hash codes stored in a hash table.
    private static void ConvertToHashTable(SecurityElement xmlElement)
        // Create a hash table to hold hash codes of the security elements.
        Hashtable xmlAsHash = new Hashtable();
        int rootIndex = xmlElement.GetHashCode();
        xmlAsHash.Add(rootIndex, "root");

        int parentNum = 0;

        foreach(SecurityElement xmlParent in xmlElement.Children)
            xmlAsHash.Add(xmlParent.GetHashCode(), "parent" + parentNum);
            if ((xmlParent.Children != null) && 
                (xmlParent.Children.Count > 0))
                int childNum = 0;
                foreach(SecurityElement xmlChild in xmlParent.Children)
                    xmlAsHash.Add(xmlChild.GetHashCode(), "child" + childNum);

    // Delete the specified security element if the current time is past
    // the time stored in the destroytime tag.
    private static SecurityElement DestroyTree(SecurityElement xmlElement)
        SecurityElement localXmlElement = xmlElement;
        SecurityElement destroyElement = 

        // Verify that a destroytime tag exists.
        if (localXmlElement.SearchForChildByTag("destroytime") != null)
            // Retrieve the destroytime text to get the time 
            // the tree can be destroyed.
            string storedDestroyTime =

            DateTime destroyTime = DateTime.Parse(storedDestroyTime);
            if (DateTime.Now > destroyTime)
                localXmlElement = null;
                Console.WriteLine("The XML security tree has been deleted.");

        // Verify that xmlElement is of type SecurityElement.
        if (xmlElement.GetType().Equals(
            // Determine whether the localXmlElement object 
            // differs from xmlElement.
            if (xmlElement.Equals(localXmlElement))
                // Verify that the tags, attributes and children of the
                // two security elements are identical.
                if (xmlElement.Equal(localXmlElement))
                    // Return the original security element.
                    return xmlElement;

        // Return the modified security element.
        return localXmlElement;
// This sample produces the following output:
// The security XML tree named RootTag(XML security tree) 
// was created on 2/23/2004 1:23:00 PM and contains 2 child elements.
//<RootTag creationdate="2/23/2004 1:23:00 PM">XML security tree
//   <destroytime>2/23/2004 1:23:01 PM</destroytime>
//   <WindowsMembership.WindowsRole version="1.00"
//                                  creationdate="2/23/2004 1:23:00 PM">
//      <BabyElement>This is a child element.</BabyElement>
//   </WindowsMembership.WindowsRole>
//This sample completed successfully; press Exit to continue.

.NET Framework
Available since 1.1

Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Return to top