如何从XML Schema控制Xml?

时间:2010-12-28 15:59:09

标签: c# xml

我有一个XSD文件,我想从中检查我的XML。我该怎么做?提前谢谢!

 XmlTextWriter objX = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8);

    objX.WriteStartDocument();

    objX.WriteStartElement("MerchantItems");
    objX.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");

3 个答案:

答案 0 :(得分:1)

link很有帮助。

这是来自该链接的一些consoildated代码,它加载您的XML文档并根据关联的模式验证它(您只需要确保您的XML文档正确引用模式):

using System.Xml;        // for XmlTextReader and XmlValidatingReader
using System.Xml.Schema; // for XmlSchemaCollection (which is used later)

internal class Program
{
    private static
        bool isValid = true; // If a validation error occurs,
                             // set this flag to false in the
                             // validation event handler. 

    private static void Main(string[] args)
    {
        XmlReaderSettings xrs = new XmlReaderSettings();
        xrs.ValidationType = ValidationType.Schema;
        xrs.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
        xrs.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
        xrs.ValidationEventHandler += MyValidationEventHandler;

        XmlReader r = XmlReader.Create("<path to xml>", xrs);

        while (r.Read())
        {
            // Can add code here to process the content.
        }

        r.Close();

        // Check whether the document is valid or invalid.
        Console.WriteLine(isValid ? "Document is valid" : "Document is invalid");

        Console.In.ReadLine();
    }

    public static void MyValidationEventHandler(object sender,
                                                ValidationEventArgs args)
    {
        Console.Out.WriteLine("Validation {1}: {0}", args.Message, args.Severity);
        isValid = false;
    }
}

我希望这有帮助!

答案 1 :(得分:1)

尝试这样的事情。

这不是一个有效的例子,只是让你入门的东西

        using(MemoryStream ms = new MemoryStream())
        using(XmlWriter w = XmlWriter.Create(ms, null))
        {
            // ... WRITE DOCUMENT HERE ...
            XmlDocument x = new XmlDocument();
            x.Load(ms);
            x.Validate(eventHandlerForSchema);
        }

答案 2 :(得分:0)

我的建议是首先编写整个xml文件。然后,一旦完成,您可以使用XmlSchema类来验证创建的xml文档。在您编写文件的过程中,我不知道该怎么做。