c# - 修改 XmlDocument 时出现 InvalidOperationException

标签 c# .net xml

我正在尝试使用 ASP.NET 在 XML 中存储一些数据。这是我的 XML 文件。

<?xml version="1.0" encoding="utf-8" ?>
<SkillsInformation>
  <Details id="1">
    <Name>XML</Name>
    <Description>Fundamentals of XML</Description>
  </Details>
  <Details id="2">
    <Name>Java</Name>
    <Description>Fundamentals of Java</Description>
  </Details>
</SkillsInformation>

我想插入技能,但我收到错误消息,

An exception of type 'System.InvalidOperationException' occurred in System.Xml.dll but was not handled in user code.
{"The specified node cannot be inserted as the valid child of this node, because the specified node is the wrong type."}

以下是我创建 Details 元素并添加属性 id 的方法。

    XmlDocument xmlDoc = new XmlDocument();

    //Get the nodes
    XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Details");
    //Counting nodes to get count of the skill items
    idCount = nodeList.Count;

    xmlDoc.Load(Server.MapPath("skills.xml"));

    XmlElement parentElement = xmlDoc.CreateElement("Details");
    //xmlDoc.AppendChild(parentElement);

    String attributeValue = idCount++.ToString();
    XmlAttribute idAttribute = xmlDoc.CreateAttribute("id", attributeValue);
    //idAttribute.Value = attributeValue;
    parentElement.Attributes.Append(idAttribute);


    XmlAttribute nameElement = xmlDoc.CreateAttribute("Name");
    nameElement.InnerText = name.Text;

    XmlAttribute descriptionElement = xmlDoc.CreateAttribute("Description");
    descriptionElement.InnerText = description.Text;

    parentElement.AppendChild(nameElement);
    parentElement.AppendChild(descriptionElement);

    //xmlDoc.AppendChild(parentElement);

    xmlDoc.DocumentElement.AppendChild(parentElement);

    bindData();

最佳答案

在显示的 XML 中,NameDescriptionelements ,不是attributes 。要创建该 XML,您需要执行以下操作:

        var nameElement = xmlDoc.CreateElement("Name");
        nameElement.InnerText = name;

        var descriptionElement = xmlDoc.CreateElement("Description");
        descriptionElement.InnerText = description;

        parentElement.AppendChild(nameElement);
        parentElement.AppendChild(descriptionElement);

关于c# - 修改 XmlDocument 时出现 InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27552186/

相关文章:

c# - 单元测试中的期望值

c# - 如何从 linq 查询结果中忽略/删除非数字值 C#

c# - 如何将对 COM 对象的 C# 引用传递给 C++ DLL

python - Unicode解码错误: 'ascii' codec can't decode byte with reading CSV

c# - 安装 ClickOnce 应用程序时出现问题

c# - 围绕库包装 Web 服务

c# - 使用未找到的实体调用服务操作

c# - 嵌套网络应用

java - 如何调试 JBossESB?

java - 在 dom 树的第一个 child 之前添加一个新节点