根级别的数据无效。在写入时,位于第1行第1个位置。

3
这是我的添加数据到XML的代码:

IsolatedStorageFile isstore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream bookfile = new IsolatedStorageFileStream("People.xml", System.IO.FileMode.Open, isstore);

XDocument xmldetails = XDocument.Load(bookfile);
XElement books =
    new XElement("person",
    new XAttribute("id", "5"),
    new XAttribute("name", "Book Title"),
    new XAttribute("beneficiary", "Book Author"),
    new XAttribute("description", "Book Author"),
    new XAttribute("deadline", "Book Author"),
    new XAttribute("price", "Fiction"));
xmldetails.Root.Add(books);

xmldetails.Save(bookfile);
bookfile.Close();

这是 People.xml:
<?xml version="1.0" encoding="utf-8" ?>
<people>
    <person index="1" name="Zlecenie numer jeden" beneficiary="Kowalski" description="Proste zlecenie jakiejs strony czy cos" price="800" deadline="27.12.2013" />
</people>

当我点击按钮时出现以下错误:

根级别的数据无效。第 1 行,第 1 个位置。


1
发布完整的错误信息。这更可能是I/O错误而不是XML问题。 - H H
我建议尝试将XElement books = to xmldetails.Root.Add(books);中的所有内容删除。当您读取bookfile中的XML时,它可能存在错误。 - Nick Bray
完整的错误名称是: 根级别的数据无效。第4行,第10个位置。 - user1943977
1
@ukaszWróblewski:People.xml是无效的。就是这么简单。我担心由于翻译问题,您可能无法准确表达您的问题所在 - user1228
@Will:这是我的XML文件:<?xml version="1.0" encoding="utf-8"?> <people> <person index="1" name="Zlecenie numer jeden" beneficiary="Kowalski" description="Proste zlecenie jakiejs strony czy cos" price="800" deadline="27.12.2013"/> </people> 你有什么解决问题的想法吗? - user1943977
显示剩余2条评论
2个回答

1

看起来你的XML文件可能缺少根节点,而你正在尝试将子节点添加到不存在的父节点中。确保你的源XML格式正确。

顺便说一下,在你的代码中,你应该这样做:

XElement books =
            new XElement("person",
            new XAttribute("id", "5"),
            new XAttribute("name", "Book Title"),
            new XAttribute("beneficiary", "Book Author"),
            new XAttribute("description", "Book Author"),
            new XAttribute("deadline", "Book Author"),
            new XAttribute("price", "Fiction"));
xmldetails.Element("People").Add(books);

当我将您的代码替换为我的代码后,我点击按钮并收到了以下消息:NullReferenceException at line: xmldetails.Element("People").Add(books); - user1943977
我把名称从xmldetails改为“plik”,现在出现了这个错误:根级别上的数据无效。第1行,第1个位置。好棒 :| - user1943977

1

应该是这样的

xmldetails.Root.Add(books);

people 是 XML 的根元素,因此您不需要指定它。

您应该使用 Root 属性。


好的,我已经按照你的建议进行了更改。请查看此链接: http://img594.imageshack.us/img594/2263/beztytuusxw.png - user1943977
@ŁukaszWróblewski,你的xml文件是无效的!请给我展示一下xml文件内容。 - Anirudha
请检查您的独立存储中的 XML 内容。 - Anirudha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接