如何解析XSD文件

Sco*_*ain 3 c# parsing xsd

我正在编写一个代码生成工具,它将接收从Visual Studio的数据集生成器生成的XSD文件,并为每个表中的每个列创建一个自定义类.我已经了解如何实现IVsSingleFileGenerator代码生成以及如何将单个文件生成器转换为多文件生成器.然而,似乎我最麻烦的一步是应该是最简单的一步.我以前从未真正使用过XML或XML-Schema,我也不知道迭代XSD文件并读出列名和类型的正确方法是什么,因此我可以构建我的代码.

有关如何读取XSD文件的教程的任何建议?如何拉也分别任何建议xs:element表示列出来,并阅读其msprop:Generator_UserColumnName,type以及msprop:Generator_ColumnPropNameInTable从每一个元素属性.

TMN*_*TMN 9

您将要创建一个XmlSchemaSet,读取您的架构,然后编译它以创建一个信息集.完成后,您可以开始遍历文档

XmlSchemaElement root = _schema.Items[0] as XmlSchemaElement;
XmlSchemaSequence children = ((XmlSchemaComplexType)root.ElementSchemaType).ContentTypeParticle as XmlSchemaSequence;
foreach(XmlSchemaObject child in children.Items.OfType<XmlSchemaElement>()) {
    XmlSchemaComplexType type = child.ElementSchemaType as XmlSchemaComplexType;
    if(type == null) {
        // It's a simple type, no sub-elements.
    } else {
        if(type.Attributes.Count > 0) {
            // Handle declared attributes -- use type.AttributeUsers for inherited ones
        }
        XmlSchemaSequence grandchildren = type.ContentTypeParticle as XmlSchemaSequence;
        if(grandchildren != null) {
            foreach(XmlSchemaObject xso in grandchildren.Items) {
                if(xso.GetType().Equals(typeof(XmlSchemaElement))) {
                    // Do something with an element.
                } else if(xso.GetType().Equals(typeof(XmlSchemaSequence))) {
                    // Iterate across the sequence.
                } else if(xso.GetType().Equals(typeof(XmlSchemaAny))) {
                    // Good luck with this one!
                } else if(xso.GetType().Equals(typeof(XmlSchemaChoice))) {
                    foreach(XmlSchemaObject o in ((XmlSchemaChoice)xso).Items) {
                        // Rinse, repeat...
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

显然你会想要将所有子处理内容放在一个单独的方法中并递归调用它,但这应该向你展示一般流程.


Bri*_*ian 6

正如btlog所说,XSD应该被解析为XML文件.C#确实为此提供了功能.

XPath教程:http ://www.w3schools.com/xpath/default.asp
XQuery教程:http ://www.w3schools.com/xquery/default.asp
随机C#XmlDocument教程:http://www.codeproject.com/ KB/CPP/myXPath.aspx

在C#中,使用XPath/XQuery XmlDocument.特别是通过SelectSingleNode和和等的通话SelectNodes.

我建议XmlDocumentXmlTextReader,如果你的目标是要拔出特定的数据块.如果您更喜欢逐行阅读,XmlTextReader则更为合适.

更新:对于那些有兴趣使用Linq查询XML的人来说,.Net 4.0 XDocument是作为替代品引入的XmlDocument.请参阅XDocument或XmlDocument上的讨论.