首页 > 解决方案 > 尝试从节点创建 XML 文档并获得“无效的 XML 文档。该文档没有根元素。”

问题描述

我正在尝试从一些 XML 中提取单个节点并将该节点及其所有子内容写入新的 XML 文档并将其保存到磁盘。在某些情况下(例如我的测试用例)有多个符合条件的节点,并且所有节点都必须写入单独的文件。

到目前为止,我的函数中的所有内容都按预期工作,直到我将文件写入磁盘。抛出的异常是:“抛出异常:System.Xml.dll 中的‘System.Xml.XmlException’”并且附加的消息是“无效的 XML 文档。文档没有根元素。” 我该如何解决这个问题?

我添加了很多控制台输出,以表明每个阶段都按预期工作。我的功能如下:

private void ExtractQIF()
        {
            var httpClient = new HttpClient();
            int QIFFound = 0;
            try
            {
                string assetsTarget = httpAuthority + "/asset";                
                var XMLRaw = httpClient.GetStringAsync(assetsTarget);
                XmlDocument XML = new XmlDocument();
                XML.LoadXml(XMLRaw.Result);                                             
                XmlNodeList QIFDocuments = XML.GetElementsByTagName("QIFDocument"); 
                Console.WriteLine("QIF Documents found: " + QIFDocuments.Count);        // WE ARE SUCCESSFULLY FINDING QIFDOCS IN THE ASSETS REQ
                foreach (XmlNode QIFDoc in QIFDocuments)
                {
                    QIFFound++;
                    try
                    {
                        Console.WriteLine(QIFDoc.InnerXml); // Debug shizzle
                        Console.WriteLine($"Document #{QIFFound} is being saved");
                        XmlDocument OutputQIFFile = new XmlDocument();
                        OutputQIFFile.ImportNode(QIFDoc, true);
                        Console.WriteLine("Node Imported to Document"); // Debug Shizzle
                        OutputQIFFile.Save(QIFSaveLocation); // This is the bastard line that isn't working
                        Console.WriteLine($"Document {QIFFound} Saved to Disk"); // Debug Shizzle
                        //Finally we should change the file extension to .qif
                    }
                    catch (Exception balls)
                    {
                        Console.WriteLine("COULD NOT EXTRACT QIF: Failed at document " + QIFFound);
                        Console.WriteLine(balls.Message);
                    }

                }
                Console.WriteLine("All QIF written to disk");                
            }
            catch
            { MessageBox.Show("COULD NOT EXTRACT ALL QIF");}

        }

相关控制台信息如下:

QIF Documents found: 2
<QPId xmlns="http://qifstandards.org/xsd/qif3">ec871a54-5bb5-470b-9ff7-de757d7726a1</QPId><Version xmlns="http://qifstandards.org/xsd/qif3"><TimeCreated>2019-01-22T15:51:20.874+00:00</TimeCreated></Version><Header xmlns="http://qifstandards.org/xsd/qif3">.... Blah Blah Blah, a shit tonne of XML
Document #1 is being saved
Node Imported to Document
Exception thrown: 'System.Xml.XmlException' in System.Xml.dll
COULD NOT EXTRACT QIF: Failed at document 1
Invalid XML document. The document does not have a root element.
<QPId xmlns="http://qifstandards.org/xsd/qif3">27400291-ea3d-41de-afee-69d186c4288f</QPId><Version xmlns="http://qifstandards.org/xsd/qif3"><TimeCreated>2019-01-22T15:50:16.827+00:00</TimeCreated></Version><Header xmlns="http://qifstandards.org/xsd/qif3"><Application> .... Blah Blah Bla, a shit tonne of XML
Document #2 is being saved
Node Imported to Document
Exception thrown: 'System.Xml.XmlException' in System.Xml.dll
COULD NOT EXTRACT QIF: Failed at document 2
Invalid XML document. The document does not have a root element.
All QIF written to disk

我也尝试将节点附加到文档本身,但围绕它们的错误和建议似乎让我回到了我在上面尝试实现它的方式。

在我看来,节点已正确填充。有任何想法吗?

标签: c#xmlqif

解决方案


根据docsImportNode仅制作指定节点的副本并返回它,它实际上并没有将其插入到文档中。您可以在给出的示例中看到需要添加的节点。

因此,要完成这项工作,您需要进行更改以执行以下操作:

var outputQIFFile = new XmlDocument();

var newQifNode = outputQIFFile.ImportNode(QIFDoc, true);

outputQIFFile.AppendChild(newQifNode);

outputQIFFile.Save(QIFSaveLocation);

但是,正如评论中所建议的,我强烈建议您查看 LINQ to XML(XDocument和朋友)。这是一个更加现代和用户友好的 API。


推荐阅读