例外:必须在文档根元素之前定义DTD

时间:2016-08-11 09:32:22

标签: c# xml dtd

我正在使用以下代码生成XML文档。在行

xmlDocument.LoadXml(end);

抛出异常说:必须在文档根元素

之前定义DTD

所以我发现xmlDocument.DocumentType为null,并且必须将实现的文档类型定义(DTD)添加到xmldocument对象。所以我添加了

 xmlDocument.CreateDocumentType("sample", null, null, null);

但它仍会引发同样的异常。

CODE:

            XmlDocument xmlDocument = new XmlDocument()
            {
                PreserveWhitespace = true
            };
            XmlElement soap = SoapUtil.ToSoap(samlMessage.GetXml(), xmlDocument);
            xmlDocument.AppendChild(soap);
            object[] outerXml = new object[] { xmlDocument.OuterXml };
            SamlTrace.Log(LogLevel.Verbose, "SOAP request to send: {0}", outerXml);
            webRequest.Method = "POST";
            webRequest.ContentType = "text/xml";
            webRequest.Headers.Add("SOAPAction", "http://oasis-open.org/committees/security");
            using (Stream requestStream = webRequest.GetRequestStream())
            {
                xmlDocument.Save(requestStream);
            }
            using (WebResponse response = webRequest.GetResponse())
            {
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
                {
                    string end = streamReader.ReadToEnd();
                    SamlTrace.Log(LogLevel.Verbose, "Received SOAP response message: {0}", new object[] { end });
-------->           xmlDocument.LoadXml(end); //exception thrown at this line
                }
            }
            XmlElement xmlElement1 = SoapUtil.FromSoap(xmlDocument.DocumentElement);
            object[] objArray = new object[] { xmlElement1.OuterXml };
            SamlTrace.Log(LogLevel.Verbose, "Response converted from SOAP message: {0}", objArray);
            xmlElement = xmlElement1;

更新1:

 xmlDocument.LoadXml(streamReader.ReadToEnd().ToString());

我通过了streamReader并将其转换为字符串。 现在它抛出了一个新的异常。

缺少根元素。

0 个答案:

没有答案