using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;namespace Test_XML
{
class Program
{
static void Main(string[] args)
{
string FileName = "G:\\C# Language Refence Demo\\book.xml";
FileStream fs;
if (!File.Exists(FileName))
{
fs = File.Create(FileName);
fs.Close();
}
XmlDocument doc = new XmlDocument();
doc.Load(FileName);
XmlElement root = doc.CreateElement("book");
doc.AppendChild(root);
XmlElement newbook = doc.CreateElement("lovel");
newbook.SetAttribute("nid", "4");
newbook.SetAttribute("font", "bold");
root.AppendChild(newbook); XmlElement newbook_name = doc.CreateElement("name");
newbook_name.SetAttribute("book_price", "5.00");
newbook.AppendChild(newbook_name);
doc.Save(FileName);
}
}
}
这段代码问题出在哪儿?为什么总是提示 缺少根节点???
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;namespace Test_XML
{
class Program
{
static void Main(string[] args)
{
string FileName = "G:\\C# Language Refence Demo\\book.xml";
FileStream fs;
if (!File.Exists(FileName))
{
fs = File.Create(FileName);
fs.Close();
}
XmlDocument doc = new XmlDocument();
doc.Load(FileName);
XmlElement root = doc.CreateElement("book");
doc.AppendChild(root);
XmlElement newbook = doc.CreateElement("lovel");
newbook.SetAttribute("nid", "4");
newbook.SetAttribute("font", "bold");
root.AppendChild(newbook); XmlElement newbook_name = doc.CreateElement("name");
newbook_name.SetAttribute("book_price", "5.00");
newbook.AppendChild(newbook_name);
doc.Save(FileName);
}
}
}
这段代码问题出在哪儿?为什么总是提示 缺少根节点???
还有你的book.xml里面是如何的?
xml里面什么也没有。是空的
newbook.SetAttribute("font", "bold");Attribute 需要创建。
xml里面什么也没有。是空的在xml里寫好xml聲明建立好根節點,再插入子節點,不然就自己在插入子節點之前用代碼把xml的聲明先寫上
You can not load a XML document if it is nothing inside.
So, update your code like this: (Make sure you delete your book.xml file first)
======================
string FileName = "G:\\C# Language Refence Demo\\book.xml";
FileStream fs;
--------------------------
XmlDocument doc = new XmlDocument();
if (!File.Exists(FileName))
{
fs = File.Create(FileName);
fs.Close();
}else
doc.Load(FileName);
---------------------
XmlElement root = doc.CreateElement("book");
doc.AppendChild(root);
XmlElement newbook = doc.CreateElement("lovel");
newbook.SetAttribute("nid", "4");
newbook.SetAttribute("font", "bold");
root.AppendChild(newbook);
XmlElement newbook_name = doc.CreateElement("name");
newbook_name.SetAttribute("book_price", "5.00");
newbook.AppendChild(newbook_name);
doc.Save(FileName);
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("book");
doc.AppendChild(root);
XmlElement newbook = doc.CreateElement("lovel");
newbook.SetAttribute("nid", "4");
newbook.SetAttribute("font", "bold");
root.AppendChild(newbook); XmlElement newbook_name = doc.CreateElement("name");
newbook_name.SetAttribute("book_price", "5.00");
newbook.AppendChild(newbook_name);
doc.Save(FileName);