大家好,我遇到了一个问题,需要加载XML文件。
我的代码如下:
Stream.Seek(0, SeekOrigin.Begin);
xmlDoc.Load(Stream); //--> throw XmlException (multiple root elements in 14,22)
xmlDoc.PreserveWhitespace = true;
XML文件是什么?
<soapenv:Envelope xmlns:dummy="
http://www.somedomian.com/dummybus/" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header Id="IDH">
<dummy:authentication>
<id>Unique</id>
<userid>myuser</userid>
</dummy:authentication>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsu:Timestamp>
<wsu:Created>2015-09-07T12:21:15</wsu:Created>
<wsu:Expires>2015-09-08T12:21:15</wsu:Expires>
</wsu:Timestamp>
</wsse:Security>
</soapenv:Header> <!--- This is line 14 and > is a column 22--->
<soapenv:Body>
<dummy:dummybus>
<msg>X1</msg>
</dummy:dummybus>
</soapenv:Body>
</soapenv:Envelope>
<Envelope>
标签是文件的根标签,为什么会出现这个错误,我该如何读取我的文件?
我发现了一些有趣的东西
当我保存文件时,它并没有像预期那样完美地加载到流中。
xmlDoc.Load(urlToFile);
xmlDoc.PreserveWhitespace = true;
看起来错误只出现在Stream中,为什么呢?
这个方法将xml字符串转换为MemoryStream。
public class XmlUtil
{
public static MemoryStream GenerateStreamFromString(string s)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
MemoryStream
时禁用(或启用)BOM:参见https://dev59.com/KHE95IYBdhLWcg3wI6jt - dbc