简体   繁体   中英

"Data at the root level is invalid. Line 1, position 1" When Parsing XML

I am wanting to parse the following xml to get richTextBox1 so show 'John Smith', '35', 'Jpeg'.

<?xml version="1.0" encoding="utf-8" ?> 
- <Games>
- <Gamer Name="John Smith" Age="35" Win%="5.33502797236373">
   <Picture-id>Jpeg</Picture-id> 
   <Game>300</Game> 
  </Gamer>
</Games>

I have used the following code to try and do this -

StringBuilder output = new StringBuilder();

String xmlString = @"Gamer.xml";

// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
    reader.ReadToFollowing("Gamer");
    reader.MoveToFirstAttribute();
    string genre = reader.Value;
    output.AppendLine("Name" + "Age");

    reader.ReadToFollowing("Picture-id");
    output.AppendLine(reader.ReadElementContentAsString());
}

richTextBox1.Text = output.ToString();

For some reason when I execute it brings back the error - 'Data at the root level is invalid. Line 1, position 1.' How can I get this to work, any input is greatly appreciated.

StringReader reads a literal string. You are trying to parse the string "Gamer.xml", not the contents of the file.

Use StreamReader instead.

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