来自带有内联Xsd的XML文件的XmlSchema对象

时间:2010-10-28 15:30:58

标签: .net xml xsd .net-4.0

在.Net中,我试图从嵌入式Xsd的Xml文件中获取XmlSchema对象,但无法找到如何操作?有人知道吗?

例如,如果它只是一个Xml文件,我可以使用XmlSchemaInference类来推断模式,或者如果它是一个Xsd,我可以使用XmlSchema类,但无法找到内联的Xsd。

示例文件位于http://pastebin.com/7yAjz4Z4(由于某种原因,此处不会显示)

谢谢

2 个答案:

答案 0 :(得分:1)

这可以通过获取XmlReader元素节点的xs:schema并将其传递给XmlSchema.Read来完成。

using System;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;

namespace EmbeddedXmlSchema
{
    class Program
    {
        static void Main(string[] args)
        {
            XNamespace xs = "http://www.w3.org/2001/XMLSchema";
            XDocument doc = XDocument.Load("XMLFile1.xml");
            XmlSchema sch;
            using (XmlReader reader = doc.Element("ReportParameters").Element(xs + "schema").CreateReader())
            {
                sch = XmlSchema.Read(reader, null);
            }
        }
    }
}

(如果您使用的是XmlDocument而不是XDocument,请查看XmlNode.CreateNavigator().ReadSubtree()

答案 1 :(得分:0)

我最后还是这样做了。非常感谢你的帮助。

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(file);

            XmlNodeList nodes =
                xmlDocument.GetElementsByTagName("schema", "http://www.w3.org/2001/XMLSchema");

            if (null != nodes && 0 != nodes.Count)
            {
                XmlReader reader = new XmlNodeReader(nodes[0]);
                XmlSchema schema = XmlSchema.Read(reader, null);

                // do stuff with schema 
            }
            else
            {
                throw new InvalidOperationException("No inline schema found.");
            }