【问题标题】:XmlDocument.Load multiple root elementsXmlDocument.Load 多个根元素
【发布时间】:2015-12-03 07:19:51
【问题描述】:

大家好,我在需要加载 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>

&lt;Envelope&gt; 标记是文件的根,为什么会发送此错误以及如何读取我的文件?

我发现了一些有趣的东西

当我保存文件时,不是将它保存在 Stream 中,而是完美加载

xmlDoc.Load(urlToFile);
xmlDoc.PreserveWhitespace = true;

看来错误只发生在Stream中,为什么?

此方法将String中的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;
        }

【问题讨论】:

  • 我没有看到任何多个根元素。顺便说一句,你为什么要抛出那个异常?
  • 我无法重现您的异常。见dotnetfiddle.net/vgMXob
  • Stream 来自哪里?你是如何创建它的?
  • @dbc 这是一个非常罕见的错误,我编辑了帖子,似乎如果你从字符串加载完美,如测试所示
  • @jasilva - 在发表评论之前,我阅读了您最近的编辑。这就是为什么我要询问Stream 的出处。

标签: c# xml


【解决方案1】:

由于您正在从流中读取数据,因此我假设当您调用 xmlDoc.Load(Stream) 时它不会位于开头。通话前你在做什么?

如果您的流支持搜索,您可以尝试在调用之前回到它的开头:

Stream.Seek(0, SeekOrigin.Begin);
xmlDoc.Load(Stream);

【讨论】:

  • 加载前我有这个代码Stream.Seek(0, SeekOrigin.Begin);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多