简体   繁体   English

如何使用ExecuteXmlReader正确输出XML数据

[英]How can i correctly output XML-data with ExecuteXmlReader

I have an ASP.NET 4.0 Application and i try to use the function ExecuteXmlReader from the SQLCommand class to get a XML-result. 我有一个ASP.NET 4.0应用程序,我尝试使用SQLCommand类中的ExecuteXmlReader函数来获取XML结果。 The query don't produce any error. 查询不会产生任何错误。 The query ends with FOR XML AUTO, ELEMENTS, ROOT('root') . 查询以FOR XML AUTO, ELEMENTS, ROOT('root')结尾。 But when i try this: 但是当我尝试这个:

Dim XML As XElement = XElement.Load(query.ExecuteXmlReader)
XML.Save(HttpContext.Current.Server.MapPath("~/Result.xml"))

i get this errormessage: 我收到此错误消息:

The XmlReader must be on a node of type Element instead of a node of type None. XmlReader必须位于Element类型的节点上,而不是None类型的节点上。 (english translation) (英文翻译)

Der XmlReader muss sich auf einem Knoten vom Typ 'Element' befinden, nicht auf einem Knoten vom Typ 'None'. Der XmlReader可以在Knoten vom Typ'Element'中找到最好的名称,而在Knoten vom Typ'None'中则可以。 (german translation) (德语翻译)

It is strange that the error occures at the line with XElement.Load(query.ExecuteXmlReader) . 奇怪的是,错误发生在XElement.Load(query.ExecuteXmlReader) But the code runs further! 但是代码运行得更远! It also saves xml-data to disk! 它还将xml数据保存到磁盘! how can this happen and how can i read out the xml-result without an error? 这怎么可能发生,我怎么能没有错误地读出xml结果?

I had similar issues with multiple FOR XML AUTO statements reading. 我在读取多个FOR XML AUTO语句时遇到了类似的问题。 Problem was solved passing XmlReader to System.Xml.XPath.XPathDocument: 解决了将XmlReader传递给System.Xml.XPath.XPathDocument的问题:

 public static XDocument MultipleNodes(XmlReader reader, string RootName = "Root")
    {
        var doc = new XDocument(new XElement(RootName));

        var xn = new XPathDocument(reader).CreateNavigator();
        XPathNodeIterator iterator = xn.Select("/*");   // Level 1 multiple Elements
        foreach (XPathNavigator item in iterator)
        {
            doc.Root.Add(XElement.Load(item.ReadSubtree()));
        }

        return doc;
    }

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

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