开发者

XmlSchema object from an XML file with inlined Xsd

开发者 https://www.devze.com 2023-01-22 15:35 出处:网络
In .Net, I\'m trying to get a XmlSchema object from Xml file with an embedded Xsd and can not find out how to do it? anybody know?

In .Net, I'm trying to get a XmlSchema object from Xml file with an embedded Xsd and can not find out how to do it? anybody know?

For example if it just an Xml file I can Infer Schema using the XmlSchemaInference class or if its a Xsd I can use XmlSchema class, but can not find away with inlined Xsd.

example file is at http://pastebin.com/7yAjz4开发者_StackOverflow社区Z4 (for some reason wouldn't show on here)

Thank you


This can be done by obtaining an XmlReader for the xs:schema element node and passing it to 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);
            }
        }
    }
}

(If you are using XmlDocument instead of XDocument, look into XmlNode.CreateNavigator().ReadSubtree().)


I went for this in the end. Thank you very must for your help.

            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.");
            }
0

精彩评论

暂无评论...
验证码 换一张
取 消