C#中的xml阅读器异常

时间:2017-01-03 07:17:30

标签: c# xml xmlreader

我创建了以下代码来读取xml文件

XML文件是:

XML file

请在我错误的地方纠正我。

   private void fetch_file_names()
    {

        string url = "http://mypersonalsite.com/test.php"; //url changed



        WebRequest myWebRequest = WebRequest.Create(url);

        WebProxy myProxy = new WebProxy();
        // Obtain the Proxy Prperty of the  Default browser.  
        myProxy.Address = new Uri("http://1.2.3.4:8080");
        myProxy.Credentials = new NetworkCredential("john.doe", "mysecretpass");
        myWebRequest.Proxy = myProxy;


        WebResponse myWebResponse = myWebRequest.GetResponse();
        Stream mystream = myWebResponse.GetResponseStream();


        XmlReaderSettings settings = new XmlReaderSettings();
        settings.DtdProcessing = DtdProcessing.Parse;


        XmlReader reader = XmlReader.Create(mystream, settings);

        reader.MoveToContent();
        // Parse the file and display each of the nodes.
        while (reader.Read())
        {
            switch (reader.NodeType)
            {
                case XmlNodeType.Element:
                    Console.Write("<{0}>", reader.Name);
                    break;
                case XmlNodeType.Text:
                    Console.Write(reader.Value);
                    break;
                case XmlNodeType.CDATA:
                    Console.Write("<![CDATA[{0}]]>", reader.Value);
                    break;
                case XmlNodeType.ProcessingInstruction:
                    Console.Write("<?{0} {1}?>", reader.Name, reader.Value);
                    break;
                case XmlNodeType.Comment:
                    Console.Write("<!--{0}-->", reader.Value);
                    break;
                case XmlNodeType.XmlDeclaration:
                    Console.Write("<?xml version='1.0'?>");
                    break;
                case XmlNodeType.Document:
                    break;
                case XmlNodeType.DocumentType:
                    Console.Write("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value);
                    break;
                case XmlNodeType.EntityReference:
                    Console.Write(reader.Name);
                    break;
                case XmlNodeType.EndElement:
                    Console.Write("</{0}>", reader.Name);
                    break;
            }
        }



        reader.Close();
        //  List<News> lmynews=new List<News>();


    }

当我尝试阅读上述XML时,会发生以下异常:

意外的XML声明。 XML声明必须是文档中的第一个节点,并且不允许在其前面显示空白字符。第2行,第3位。

0 个答案:

没有答案