此操作将创建结构不正确的文档 [英] This operation would create an incorrectly structured document

查看:43
本文介绍了此操作将创建结构不正确的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是XML的新手,并尝试了以下操作,但出现异常.有人能帮我吗?

I am new to XML and tried the following but I'm getting an exception. Can someone help me?

例外是This operation would create an incorrectly structured document

我的代码:

string strPath = Server.MapPath("sample.xml");
XDocument doc;
if (!System.IO.File.Exists(strPath))
{
    doc = new XDocument(
        new XElement("Employees",
            new XElement("Employee",
                new XAttribute("id", 1),
                    new XElement("EmpName", "XYZ"))),
        new XElement("Departments",
            new XElement("Department",
                new XAttribute("id", 1),
                    new XElement("DeptName", "CS"))));

    doc.Save(strPath);
}

推荐答案

Xml文档必须只有一个根元素.但是,您尝试在根级别同时添加DepartmentsEmployees节点.添加一些根节点来解决此问题:

Xml document must have only one root element. But you are trying to add both Departments and Employees nodes at root level. Add some root node to fix this:

doc = new XDocument(
    new XElement("RootName",
        new XElement("Employees",
            new XElement("Employee",
                new XAttribute("id", 1),
                new XElement("EmpName", "XYZ"))),

        new XElement("Departments",
                new XElement("Department",
                    new XAttribute("id", 1),
                    new XElement("DeptName", "CS"))))
                );

这篇关于此操作将创建结构不正确的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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