我正在尝试使用 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 中,Name
和 Description
为 elements ,不是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/