尝试读取 XML 文档 (C#) 时出错?

Error trying to read an XML Document(C#)?

我有以下 XML 我正在尝试 "load" 到 XmlDocument 对象中:Link to XML File

我有以下方法代码来加载 XML 文档:

public XmlDocument getDirections()
    {
        XmlTextReader xmlReader;
        XmlDocument xmlResponse = new XmlDocument();
        StringBuilder xmlResponseString = new StringBuilder();
        xmlReader = new XmlTextReader(getRequestURL()); //getRequestURL gives the URL for XML doucument

        while (xmlReader.Read())
        {
            if (xmlReader.NodeType == XmlNodeType.Element)
            {
                xmlResponseString.Append(xmlReader.ReadInnerXml());
            }
        }
        xmlResponse.LoadXml(xmlResponseString.ToString());
        return xmlResponse;
     }

当我 运行 代码时,出现以下错误:

An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll

Additional information: There are multiple root elements. Line 3, position 3.

我认为这是因为 XML 文档有多个 route 对象,但我不知道如何修复它。任何帮助将不胜感激!

它说的那一行:

Additional information: There are multiple root elements. Line 3, position 3.

这是你的线索。

格式正确 XML 将有 1 个根元素。

例如

<root>
   <child>
     <subchild>.....</subchild>
   </child>
</root>

请参阅进一步说明:http://www.w3schools.com/xml/xml_syntax.asp

这样做有什么意义?使用内置功能从 Url:

获取 Xml
var str = @"https://maps.googleapis.com/maps/api/directions/xml?origin=Jamaica,%20NY%2011418&destination=Hunter%20College%20Park%20Avenue%20New%20York&mode=&alternatives=true&key=AIzaSyB8G9omVUu6a_OQCrRM-QItdwk-Hxq__mg";

var doc = new XmlDocument();
doc.Load(str);

//or
var xdoc = XDocument.Load(str);

我会研究 Linq to Xml (XDocument) 而不是 XmlDocument。使用起来要容易得多。

您可以使用以下代码段加载 xml。

public XmlDocument getDirections()
    {
        XmlTextReader xmlReader;
        XmlDocument xmlResponse = new XmlDocument();
        StringBuilder xmlResponseString = new StringBuilder();
        HttpWebRequest request =HttpWebRequest.Create(getRequestURL());

        using(HttpWebResponse response = (HttpWebResponse) request.GetResponse())
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                using (var responseStream = response.GetResponseStream())
                {
                    xmlResponse.Load(responseStream);
                }
            }
        }            
        xmlResponse.LoadXml(xmlResponseString.ToString());
        return xmlResponse;
    }

我在尝试使用 XmlReader 阅读 Xml 时遇到了类似的事件。

我的代码:

using (XmlReader reader = XmlReader.Create(new StringReader(filesContent)))
{
    while (reader.Read())     //<--- This is where the exception was caught
    {
        // Do stuff here
    }
}

捕获异常:

An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll

Additional information: There are multiple root elements. Line X, position Y.

注意:异常中提供的有关行的位置和位置的信息不是我的附加根所在的 xml 文件内容中的实际行或位置, 这有点误导。

一个格式正确的 xml 文件应该 只包含一个根目录 。因此:

<?xml version="1.0" encoding="UTF-8" ?> 
<root1>
   <child1>
     <subchild1>.....</subchild1>
   </child1>
</root1>

在我的例子中,抛出异常是因为 我的 xml 文件包含 2 个根 .

<?xml version="1.0" encoding="UTF-8" ?>
<root1>
   <child1>
     <subchild1>.....</subchild1>
   </child1>
</root1>
<root2>
   <child1>
     <subchild1>.....</subchild1>
     <subchild2>.....</subchild2>
   </child1>
   <child2>
     <subchild1>.....</subchild1>
   </child2>
</root2>

这可以很容易地通过在文件中添加一些 'parentroot' 来解决,使 2 个根嵌套在新的父根下

<?xml version="1.0" encoding="UTF-8" ?>
<parnetroot>    
    <root1>
       <child>
         <subchild>.....</subchild>
       </child>
    </root1>
    <root2>
       <child1>
         <subchild1>.....</subchild1>
         <subchild2>.....</subchild2>
       </child1>
       <child2>
         <subchild1>.....</subchild1>
       </child2>
    </root2>
</parnetroot>