【问题标题】:LINQ to XML is throwing an exception and I can't figure out why [duplicate]LINQ to XML 抛出异常,我不知道为什么[重复]
【发布时间】:2015-05-28 19:21:03
【问题描述】:

我有一个看起来像这样的 XML 文件

<DatabaseInfo>
    <DatabaseInformation>
        <name>\\server\path\HelpDesk.accdb</name>
    </DatabaseInformation>
</DatabaseInfo>
<ShortcutPath>
    <ShortcutPathInformation>
        <name>Y:\Shortcuts</name>
    </ShortcutPathInformation>
</ShortcutPath>

我的 C# 代码看起来像

var result = (from ele in XDocument.Load(@"C:\Srptupd\Database.xml").Descendants("DatabaseInformation")
              select ele).FirstOrDefault();
if (result != null)
{
    //
}

我得到一个例外说

There are multiple root elements. Line 6, position 2.

如何获取 DatabaseInformation 和 ShortcutPathInformation 的名称值?

【问题讨论】:

  • 如果上面的数据是你所有的数据,那么它不是有效的 XML。 XML 必须只有一个根元素。
  • XML 有两个根元素——DatabaseInfoShortcutPath。 XML 文档必须有one single root。在这里尝试阅读具有多个片段的文档:stackoverflow.com/questions/2374426/…

标签: c# xml linq linq-to-xml


【解决方案1】:

发生这种情况是因为 XML 文档需要恰好有一个顶级“根”元素。另一方面,您的文档有两个顶级元素 - 即 DatabaseInfoShortcutPath

您需要将 XML 文档修复为具有单个顶部元素。您可以通过添加人工根或将 XML 分成两部分来做到这一点。

以下是添加人工根的方法:

<?xml version="1.0" encoding="UTF-8"?>
<DbAndShortcuts>
    <DatabaseInfo>
        <DatabaseInformation>
            <name>\\server\path\HelpDesk.accdb</name>
        </DatabaseInformation>
    </DatabaseInfo>
    <ShortcutPath>
        <ShortcutPathInformation>
            <name>Y:\Shortcuts</name>
        </ShortcutPathInformation>
    </ShortcutPath>
</DbAndShortcuts>

将文档分成两部分可能是另一种有效的解决方案:

<?xml version="1.0" encoding="UTF-8"?>
<!-- C:\Srptupd\Database.xml -->
<DatabaseInfo>
    <DatabaseInformation>
        <name>\\server\path\HelpDesk.accdb</name>
    </DatabaseInformation>
</DatabaseInfo>

<!-- C:\Srptupd\Shortcut.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<ShortcutPath>
    <ShortcutPathInformation>
        <name>Y:\Shortcuts</name>
    </ShortcutPathInformation>
</ShortcutPath>

【讨论】:

  • 谢谢。我不敢相信答案这么简单。我以为这是我的代码 :)
猜你喜欢
  • 1970-01-01
  • 2020-01-15
  • 2012-01-30
  • 1970-01-01
  • 2021-10-07
  • 2011-07-19
  • 2016-11-27
  • 2016-07-28
  • 1970-01-01
相关资源
最近更新 更多