简体   繁体   中英

Load xml using XDocument.Load error “root element is missing” from stream

I got problems in using XDocument.Load because sometimes there is no error and sometimes there is already error, same error "root element is missing" I already tried using seek and position still the same error occurs.

Any ideas how can I fix this issue? Thanks

Here is my source code so far:

using (var stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            stream.Seek(0, System.IO.SeekOrigin.Begin);
            //stream.Position = 0;
            var request = XDocument.Load(stream);
            var get_command = from r in request.Descendants("Transaction")
                              select new
                              {
                                  Type = r.Element("Type").Value
                              };

            foreach (var c in get_command)
            {
                type = c.Type;
            }
        }

Sample XML

<?xml version="1.0" encoding="utf-8"?>
<Request>
  <Transaction>
    <Type>gc</Type>
  </Transaction>
</Request>

My guess would be your sample is over simplified and your Xml looks more like this

<?xml version="1.0" encoding="utf-8"?>
<Request>
  <Transaction>
    <Type>gc</Type>
  </Transaction>
</Request>
<Request>
  <Transaction>
    <Type>gc</Type>
  </Transaction>
</Request>

That would explain your error as there is no root element. You need to make it like this

<?xml version="1.0" encoding="utf-8"?>
<Requests>
  <Request>
    <Transaction>
      <Type>gc</Type>
    </Transaction>
  </Request>
  <Request>
    <Transaction>
      <Type>gc</Type>
    </Transaction>
  </Request>
</Requests>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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