简体   繁体   English

C#使用公共DTD提取XML数据

[英]C# Extracting an XML data with public DTD

The XML file is created with a public DTD. XML文件是使用公共DTD创建的。 The XML can have different locations therefore when i'm going to read the XML file, i get an error like "Couldn't find dtd file". XML可以具有不同的位置,因此,当我要读取XML文件时,会出现类似“找不到dtd文件”的错误。 DTD path set in XML is dependent on the XML location and it's not ideal to create a DTD file in w/c the XML files are located. 在XML中设置的DTD路径取决于XML的位置,因此不理想的是在XML文件所在的位置创建DTD文件。

So i'm thinking to create a copy of an XML file with a new DTD declaration where the DTD path is set to my local directory where the DTD is located but i don't know how and i'm not sure if this would fix my problem. 因此,我正在考虑使用新的DTD声明创建XML文件的副本,其中DTD路径设置为DTD所在的本地目录,但我不知道如何,并且不确定是否可以解决此问题我的问题。 I'm currently using XmlDocument to extract some XMl data. 我当前正在使用XmlDocument提取一些XMl数据。

I tried searching a solution online but i couldn't find any to solve my problem. 我尝试在线搜索解决方案,但找不到任何解决方案。

Any help would be greatly appreciated. 任何帮助将不胜感激。

Thanks in advance. 提前致谢。

I think this have to work: 我认为这必须起作用:

    private string msValidationError;
    public string validateXML(XmlTextReader reader, string sDTDPath)
    {
        System.Xml.XmlReaderSettings oSettings = new System.Xml.XmlReaderSettings();
        oSettings.ValidationType = ValidationType.DTD;
        oSettings.ValidationEventHandler += ValidationCallBack;
        System.IO.Directory.SetCurrentDirectory(sDTDPath); //Set dtd folder             

        System.Xml.XmlReader oReader = System.Xml.XmlReader.Create(reader, oSettings);
        try
        {
            msValidationError = "";
            while (oReader.Read())
            {
            }
            oReader.Close();
            if (!string.IsNullOrEmpty(msValidationError))
            {
                return string.Format("Invalid xml! {0}",msValidationError);
            }
        }
        catch (Exception ex)
        {
            return "Invalid xml.";
        }
        finally
        {
            try
            {
                oReader.Close();
            }
            catch (Exception exI)
            {                    
            }
        }
        return msValidationError;
    }

    private void ValidationCallBack(object sender, System.Xml.Schema.ValidationEventArgs args)
    {   
        msValidationError = msValidationError + args.Message;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM