日期:2014-05-18 浏览次数:21105 次
public void EditXmlFile()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("yourFile");
XmlNode root = xmlDoc.DocumentElement;
//if (root.HasChildNodes)
//{
// return node.ChildNodes;
//}
///
EditNode(root, "Book", "mingcheng", xmlDoc);
xmlDoc.Save("yourFile");
}
private void EditNode(XmlNode node, string newName, string oldName, XmlDocument xmlDoc)
{
if(node.Name == oldName)
{
XmlNode newNode = xmlDoc.CreateNode(newName, node.LocalName, node.NamespaceURI);
foreach(XmlAttribute a in node.Attributes)
{
if (a.Name == "genre")
{
XmlAttribute newAttr = xmlDoc.CreateAttribute("chuBanShe");
newAttr.Value = a.Value;
newNode.Attributes.Append(newAttr);
}
else if(a.Name != "publicationdate")
{
newNode.Attributes.Append(a);
}
}
foreach(XmlNode n in node.ChildNodes)
{
newNode.AppendChild(n);
}
XmlNode parent = node.ParentNode;
parent.ReplaceChild(newNode, node);
}
}
------解决方案--------------------
调试成功。注意,当我们Append一个XMLNode时,总是取第一个Node。
{
if (node.Name == oldName)
{
XmlNode newNode = xmlDoc.CreateNode(XmlNodeType.Element, newName, node.NamespaceURI);
XmlAttributeCollection collection = node.Attributes;
foreach (XmlAttribute a in collection)
{
if (a.Name == "genre")
this.data