0

I have an XML file that looks like

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

and my C# code looks like

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

and I get an exception saying

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

How can I get the values of name for DatabaseInformation and ShortcutPathInformation?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
software is fun
  • 7,286
  • 18
  • 71
  • 129
  • If above data is all your data, then it's not valid XML. XML must have a single root element only. – Thomas Weller May 28 '15 at 19:23
  • That XML has two root elements -- `DatabaseInfo` and `ShortcutPath`. XML documents must have [one single root](http://en.wikipedia.org/wiki/Root_element). Try here for reading a document with multiple fragments: http://stackoverflow.com/questions/2374426/linq-to-xml-load-xml-fragments-from-file – dbc May 28 '15 at 19:24

1 Answers1

2

This happens because XML documents are required to have exactly one top-level "root" element. Your document, on the other hand, has two top-level elements - namely, DatabaseInfo and ShortcutPath.

You need to fix the XML document to have a single top element. You can do this either by adding an artificial root, or by splitting your XML in two.

Here is what you do to add an artificial root:

<?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>

Splitting a document in two parts may be another valid solution:

<?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>
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523