“根级别的数据无效.第1行,位置1",解析XML时 [英] "Data at the root level is invalid. Line 1, position 1" When Parsing XML

查看:962
本文介绍了“根级别的数据无效.第1行,位置1",解析XML时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析以下xml以获得richTextBox1,因此请显示'John Smith','35','Jpeg'.

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();

由于某种原因,执行该命令会导致错误- '根级别的数据无效.第1行,位置1.'我怎样才能使它正常工作,我们将不胜感激.

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读取文字字符串.您正在尝试解析字符串"Gamer.xml",而不是文件内容.

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

改为使用StreamReader.

Use StreamReader instead.

这篇关于“根级别的数据无效.第1行,位置1",解析XML时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆