Archive

Posts Tagged ‘XML’

C# Schema Validator

December 24, 2007 Simeon Lobo Leave a comment

Can be wrapped into a reusable function for easy reuse

//The C# validator
//———————                   

System.Xml.XmlDocument objWorkingXML = new XmlDocument();

System.Xml.XmlValidatingReader objValidateXML;

System.Xml.Schema.XmlSchemaCollection objSchemasColl = new XmlSchemaCollection();

System.Xml.XmlTextReader xmlTxtReader = new System.Xml.XmlTextReader(@”..\..\rss.xsd”);

objSchemasColl.Add(“urn:simeon.com/xmlschemas/dosvis/dosvisgrouppayauthority/”, xmlTxtReader);

//This loads XML string in.. but you can also load files similarly

objValidateXML = new System.Xml.XmlValidatingReader(new XmlTextReader(@”..\..\rss.xml”));

//This is how you CATCH the errors (with a handler function)

//AddHandler objValidateXML.ValidationEventHandler, AddressOf ValidationCallBack

objValidateXML.ValidationEventHandler += new ValidationEventHandler(MyValidationEventHandler);

objValidateXML.Schemas.Add(objSchemasColl);

//This is WHERE the validation occurs.. WHEN the XML Document READS throughthe validating reader

objWorkingXML.Load(objValidateXML);

<!– The XML (rss.xml) file –>
<?xml version=1.0 ?>

<parent_node xmlns=urn:simeonlobo/ xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation=test.xsd>

</parent_node>

<!– The schema (rss.xsd) file –>
<?xml version=1.0?>

<xs:schema targetNamespace=urn:simeonlobo/ xmlns=urn:simeonlobo/  xmlns:msdata=urn:schemas-microsoft-com:xml-msdata xmlns:xs=http://www.w3.org/2001/XMLSchema elementFormDefault=qualified>

</xs:schema>

 

 

Categories: Technical Tags: , ,

Stripping XML nodes imperatively

December 22, 2007 Simeon Lobo Leave a comment

Depending on the situation and in certain circumstances, XSL transformations may be unwieldy. The ability to parse and strip custom nodes from an XML fragment is very handy in the these situations. The below code can be modified and used for this purpose,

//Strip unwanted nodes
i = ProcessFile(Server.MapPath(“Extract.xml”), “AccessControl”, String.Empty, String.Empty);

//Strip unwanted attributes
xml = StripXmlAttribute(xml, “ThesaurusTerm”);

//Strip unwanted attributes
public string StripXmlAttribute(string inputString, string nodeNameToStripAllAttributes)
{
   
return System.Text.RegularExpressions.Regex.Replace(inputString, @”<( )*” + nodeNameToStripAllAttributes +
                                                       
“([^>])*>”, “<” + nodeNameToStripAllAttributes + “>”,
                                                       
System.Text.RegularExpressions.RegexOptions.IgnoreCase);

}

    /// <summary>
    /// This function removes a specified node from the specified XML file
    /// It can search for the node based solely on name
    /// OR it can also use an attribute name to further select a node
   
/// OR it can use the attribute value to pin-point a node
   
/// </summary>

    /// <param name=”xmlFileName”>The fully qualified name of the XML file to remove the node from</param>

    /// <param name=”nodeName”>The name of the node to remove</param>

    /// <param name=”attributeName”>Optional: Any attribute name of the node to be deleted</param>

    /// <param name=”attributeValue”>Optional: Any attribute value of the above attribute</param>

    /// <returns>a int to indicate the number of nodes removed</returns>

    public int ProcessFile(string xmlFileName, string nodeName, string attributeName, string attributeValue)

    {

        XmlDocument doc = new XmlDocument();

        int removedNodeCount = 0;

        // if the node name provided is null or empty, fail

        if ((nodeName == null) || (nodeName == string.Empty))

        {

            Console.WriteLine(“Invalid node name provided”);

            return 0;

        }

        try

        {

            doc.Load(xmlFileName);

            removedNodeCount = ScanAndDeleteNodes(doc.DocumentElement, nodeName, attributeName, attributeValue);

            // if had some node removals, save the file

            if (removedNodeCount > 0)

                doc.Save(xmlFileName);

        }

        catch (XmlException xe)

        {

            Console.WriteLine(“Error loading the document”);

            Console.WriteLine(xe.Message);

            return 0;

        }

        return removedNodeCount;

    }

    /// <summary>

    /// Recursive function to scan and delete child nodes

    /// </summary>

    /// <param name=”node”>the root node to scan</param>

    /// <param name=”nodeName”>The name of the node to remove</param>

    /// <param name=”attributeName”>Optional: Any attribute name of the node to be deleted</param>

    /// <param name=”attributeValue”>Optional: Any attribute value of the above attribute</param>

    /// <returns>a int to indicate the number of nodes removed</returns>

    private int ScanAndDeleteNodes(XmlNode node, string nodeName, string attributeName, string attributeValue)

    {

        // Delete matching children of this node

        int removedNodeCount = DeleteChildren(node, nodeName, attributeName, attributeValue);

        // get the remaining children of this node

        XmlNodeList childNodes = node.ChildNodes;

        foreach (XmlNode child in childNodes)

            removedNodeCount += ScanAndDeleteNodes(child, nodeName, attributeName, attributeValue);

        return removedNodeCount;

    }

    /// <summary>

    /// Deletes Matching children of the node passed in

    /// </summary>

    /// <param name=”rootNode”>the root node to scan the child nodes to be deleted</param>

    /// <param name=”nodeName”>The name of the node to remove</param>

    /// <param name=”attributeName”>Optional: Any attribute name of the node to be deleted</param>

    /// <param name=”attributeValue”>Optional: Any attribute value of the above attribute</param>

    /// <returns>An XmlNode if found, otherwise null</returns>

    private int DeleteChildren(XmlNode rootNode, string nodeName, string attributeName, string attributeValue)

    {

        ArrayList nodesToRemove = new ArrayList();

        // find the nodes requested by the user

        foreach (XmlNode node in rootNode.ChildNodes)

        {

            if (CheckNode(node, nodeName, attributeName, attributeValue))

                nodesToRemove.Add(node);

        }

        // remove the nodes

        if (nodesToRemove.Count > 0)

        {

            foreach (XmlNode node in nodesToRemove)

                rootNode.RemoveChild(node);

        }

        return nodesToRemove.Count;

    }

    private bool CheckNode(XmlNode node, string nodeName, string attributeName, string attributeValue)

    {

        // if we have a node name match

        if (node.Name == nodeName)

        {

            // now we have a node name match

            // try to see if attribute name is specified

            // if no attribute name was specified, this is our node

            if ((attributeName == null) || (attributeName == string.Empty))

                return true;

            // the user has atleast specified attibute name

            // so lets try to see if this element has that attribute or not

            XmlAttribute attr = node.Attributes[attributeName];

            if (attr != null)

            {

                // now we have an attribute name match

                // and we need to see if attribute value is specified

                if (attributeValue == null)

                {

                    // if no attribute value was specified, then the user does not care about the value.

                    // let’s give him this node

                    return true;

                }

                else if (attr.Value == attributeValue) // we have an attribute value

                {

                    // and we have a match too

                    return true;

                } // end of else if

            } // end of attr != null

        } // // end of nodeName match

        return false;

    }

 

 

 

Categories: Technical Tags: , ,