我正在尝试使用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();
答案 0 :(得分:2)
在显示的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);