修改XmlDocument时出现InvalidOperationException

时间:2014-12-18 17:20:03

标签: 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();

1 个答案:

答案 0 :(得分:2)

在显示的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);