日期:2014-05-19  浏览次数:20913 次

xml操作的一个问题.
xml源文件:
<book> <ISBN> uy </ISBN> </book>

代码:
                        FileStream   fs   =   new   FileStream( "book.xml ",   FileMode.Open);
                        XmlReader   reader   =   XmlReader.Create(fs);
                        reader.ReadStartElement( "book ");
                        reader.ReadToFollowing( "ISBN ");
                        do
                        {
                                Console.WriteLine(reader.ReadString());

                        }   while   (reader.ReadToNextSibling( "ISBN "));
                        reader.ReadEndElement();

怎么会抛出exception:
Exception:   'None '   is   an   invalid   XmlNodeType.   Line   1,   position   29.

如果把xml改成:
<book>
          <ISBN> uy </ISBN>
</book>
就不会了,   但是项目要求不允许这么做.   如何处理?

------解决方案--------------------
xml源文件:
<book> <ISBN> uy </ISBN> </book>
这样子,应不行吧.还是让程序自动生成XML文件好些.
我以前是用
DataSet ds1= new DataSet
这个对象直接有方法.读写XML文件 很方便.
------解决方案--------------------

已知有一个XML文件(bookstore.xml)如下:
<?xml version= "1.0 " encoding= "gb2312 "?>
<bookstore>
<book genre= "fantasy " ISBN= "2-3631-4 ">
<title> Oberon 's Legacy </title>
<author> Corets, Eva </author>
<price> 5.95 </price>
</book>
</bookstore>

1、往 <bookstore> 节点中插入一个 <book> 节点:
XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load( "bookstore.xml ");
XmlNode root=xmlDoc.SelectSingleNode( "bookstore ");//查找 <bookstore>
XmlElement xe1=xmlDoc.CreateElement( "book ");//创建一个 <book> 节点
xe1.SetAttribute( "genre ", "李赞红 ");//设置该节点genre属性
xe1.SetAttribute( "ISBN ", "2-3631-4 ");//设置该节点ISBN属性

XmlElement xesub1=xmlDoc.CreateElement( "title ");
xesub1.InnerText= "CS从入门到精通 ";//设置文本节点
xe1.AppendChild(xesub1);//添加到 <book> 节点中
XmlElement xesub2=xmlDoc.CreateElement( "author ");
xesub2.InnerText= "候捷 ";
xe1.AppendChild(xesub2);
XmlElement xesub3=xmlDoc.CreateElement( "price ");
xesub3.InnerText= "58.3 ";
xe1.AppendChild(xesub3);

root.AppendChild(xe1);//添加到 <bookstore> 节点中
xmlDoc.Save( "bookstore.xml ");
//===============================================
结果为:
<?xml version= "1.0 " encoding= "gb2312 "?>
<bookstore>
<book genre= "fantasy " ISBN= "2-3631-4 ">
<title> Oberon