日期:2014-05-18  浏览次数:20887 次

一个关于XML的问题,请大家帮帮忙!在线等,马上结贴!
<?xml version='1.0'?>
<!-- This file represents a fragment of a book store inventory database -->
<bookstore>
  <book genre="autobiography" publicationdate="1991" ISBN="1-861003-11-0">
  <title>The Autobiography of Benjamin Franklin</title>
  <author>
  <first-name>Benjamin</first-name>
  <last-name>Franklin</last-name>
  </author>
  <price>8.99</price>
  </book>
</bookstore>


xml文件格式如上,如何修改元素名称/如何修改属性名称/如何删除属性?,并保证xml文件的其它内容不变!

例如:如何把元素名book改为mingcheng/如何把属性名genre改为chubanshe/如何把属性publicationdate="1991"直接去掉?
得到如下效果:

<?xml version='1.0'?>
<!-- This file represents a fragment of a book store inventory database -->
<bookstore>
  <mingcheng chubanshe="autobiography" ISBN="1-861003-11-0">
  <title>The Autobiography of Benjamin Franklin</title>
  <author>
  <first-name>Benjamin</first-name>
  <last-name>Franklin</last-name>
  </author>
  <price>8.99</price>
  </mingcheng>
</bookstore>

请大家帮帮忙,谢了!

------解决方案--------------------
本人原创,刚刚写的。

C# code

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。

C# code

  {
      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