tags:

views:

248

answers:

1

I need to add some tags to an existing XML schema and write it to file. However, I need to add tags to every of the existing schema. What is the best way to accomplish it in C#?

Thanks!

I have the following code that parses the schema:

        /// <summary>
    /// Iterates over all elements in a XmlSchema and prints them out
    /// </summary>
    /// <param name="schema"></param>
    private void IterateOverSchemaElements(XmlSchema schema)
    {
        XmlSchemaComplexType complex;
        foreach (XmlSchemaObject schemaObj in schema.Items)
        {
            complex = schemaObj as XmlSchemaComplexType;
            if (complex != null)
            {
                if (OutputTextDelegate != null)
                {
                    OutputTextDelegate(string.Format("ComplexType: {0}", complex.Name));
                }
                complex.Annotation = new XmlSchemaAnnotation();                    
                //Get sequence of the complextype:
                XmlSchemaSequence sequence = complex.ContentTypeParticle as XmlSchemaSequence;
                if (sequence != null)
                {
                    // Iterate over each XmlSchemaElement in the Items collection.
                    foreach (XmlSchemaElement childElement in sequence.Items)
                    {
                        if (OutputTextDelegate != null)
                        {
                            OutputTextDelegate(string.Format("--Element: {0}", childElement.Name));
                        }                            
                    }
                }
            }
        }
    }
+1  A: 

You may be better off manipulating the schema as an XML document, not as a schema. For instance, this code creates an annotation under every element definition that's part of a sequence in a complex type:

const string uri = "http://www.w3.org/2001/XMLSchema";
XmlDocument d = new XmlDocument();
d.Load(path);
XmlNamespaceManager ns = new XmlNamespaceManager(d.NameTable);
ns.AddNamespace("xs", uri);

foreach (XmlElement ct in d.SelectNodes("//xs:complexType", ns))
{
    foreach (XmlElement e in ct.SelectNodes("xs:sequence/xs:element", ns))
    {
        XmlElement a = d.CreateElement("xs", "annotation", uri);
        a.InnerText = String.Format(
            "Complex type: {0}; Element name: {1}",
            ct.GetAttribute("name"),
            e.GetAttribute("name"));
        e.AppendChild(a);
    }
}
Robert Rossney