zoukankan      html  css  js  c++  java
  • c#关于xml

    xml文件中thebook.ChildNodes.Count会随着thebook.ChildNodes.Item(i)的使用自动的减少

    解决方法是给记录初值

    thebook1 = xml.CreateElement("book1");
    int m = thebook.ChildNodes.Count;
    for (int i = 0; i < m; i++)
    {
      thebook1.AppendChild(thebook.ChildNodes.Item(0));
    }
    thebook.AppendChild(thebook1);

    这样就把原本的xml文件里面的

    <book category="CHILDREN">
      <title>huluwa</title>
      <author> </author>
      <year> </year>
      <price>30</price>
    </book>

    给添加了book1的子节点,成为

    <book category="CHILDREN">
      <book1>
        <title>huluwa</title>
        <author> </author>
        <year> </year>
        <price>30</price>
      </book1>
    </book>

    好了代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml;

    namespace xml实验2
    {
    class Program
    {
      static void Main(string[] args)
    {
      XmlDocument xml = new XmlDocument();
      XmlElement thebook = null, thebook1 = null, thelement = null ;

      xml.Load("Bookstore.xml");
      XmlElement root = xml.DocumentElement;

      thebook =(XmlElement)root.SelectSingleNode("/bookstore/book[@category='CHILDREN']");//获得属性category='CHILDREN' 的节点位置  属性需要加@    元素不要加

      thebook1 = xml.CreateElement("book1");
      int m = thebook.ChildNodes.Count;
      for (int i = 0; i < m; i++)
      {
        thebook1.AppendChild(thebook.ChildNodes.Item(0));
      }
      thebook.AppendChild(thebook1);


      thebook1 = xml.CreateElement("book1");//添加新元素title、author、year、price到book1
      thelement = xml.CreateElement("title");
      thelement.InnerText = "huluwa";
      thebook1.AppendChild(thelement);

      thelement = xml.CreateElement("author");
      thelement.InnerText = " ";
      thebook1.AppendChild(thelement);

      thelement = xml.CreateElement("year");
      thelement.InnerText = " ";
      thebook1.AppendChild(thelement);

      thelement = xml.CreateElement("price");
      thelement.InnerText = "30";
      thebook1.AppendChild(thelement);
      thebook.AppendChild(thebook1);

      XmlNodeList someBook = root.SelectNodes("/bookstore/book/book1[price<30]");//删除子节点价格低于30的书
      for (int j = 0; j < someBook.Count; j++)
        someBook.Item(j).ParentNode.RemoveChild(someBook.Item(j));

      XmlNodeList someBooks = root.SelectNodes("/bookstore/book[price<30]");
      for (int i = 0; i < someBooks.Count; i++)
      {
        someBooks.Item(i).ParentNode.RemoveChild(someBooks.Item(i));
      }

      xml.Save("Bookstore.xml");//记得保存  可以用xml.outerxml查看Console.WriteLine(theBook.OuterXml);

    }
    }
    }

  • 相关阅读:
    最小二乘法拟合(python numpy) Littlefish
    我的话
    亿万富豪们给2013年毕业生的忠告
    网站色彩搭配<转载>
    灾难专用使你的网站变黑为雅安默哀
    <转载>协议森林13 9527 (DNS协议)
    不常见的HTML标签<转载>
    tomcat支持shml配置详解
    <转载>struts2 拦截器 interceptor
    乱码解决
  • 原文地址:https://www.cnblogs.com/zhengbao/p/7922671.html
Copyright © 2011-2022 走看看