使用XMLReader类
XMLReader是一个抽象类,直接使用XMLReader必须使用静态方法Create,返回XMLReader对象
在读每个节点时,都要检查Nodetype属性,如果是文本就输出
XmlReader reader = XmlReader.Create("books.xml");
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Text)
{
Console.WriteLine(reader.Value+"\n\n");
}
}
ReadElementString
可以选择以元素名作为参数,只读取string类型。
示例中 如果节点类型不是element,或者名称不是title,就会调用reader()方法进入下一个节点。
在成功执行ReadElementString不需要调用reader方法,因为ReadElementString已经调用了整个Element,并定为到下一个节点
XmlReader reader2 = XmlReader.Create("books.xml");
while (!reader2.EOF)
{
if (reader2.MoveToContent() == XmlNodeType.Element && reader2.Name == "title")
{
Console.WriteLine(reader2.ReadElementString() + "\n\n");
}
else
{
reader2.Read();
}
}
如果去掉reader2.Name == "title",会出错因为MoveToContent检查到的第一个元素不包含文本类型
所以代码1可以变成
XmlReader reader2 = XmlReader.Create("books.xml");
while (!reader2.EOF)
{
if (reader2.MoveToContent() == XmlNodeType.Element )
{
try
{
Console.WriteLine(reader2.ReadElementString() + "\n\n");
}
catch (XmlException ex) { }//如果发生异常,就跳过
}
else
{
reader2.Read();
}
}
XMLReader类进行验证
可以使用XmlReaderSettings,根据XSD架构验证XML
XSD架构
去掉了XML中的一个必须节点ISBN,这样在验证时会抱错
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://www.test.com/books2" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="bookstore">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="book">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string" />
<xs:element name="author">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" name="name" type="xs:string" />
<xs:element minOccurs="0" name="first-name" type="xs:string" />
<xs:element minOccurs="0" name="last-name" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="price" type="xs:decimal" />
</xs:sequence>
<xs:attribute name="genre" type="xs:string" use="required" />
<xs:attribute name="publicationdate" type="xs:date" use="required" />
<xs:attribute name="ISBN" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
XML架构
<bookstore xmlns="http://www.test.com/books2">
<book genre="autobiography" publicationdate="1981-03-22" 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>
<book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
<title>The Confidence Man</title>
<author>
<first-name>Herman</first-name>
<last-name>Melville</last-name>
</author>
<price>11.99</price>
</book>
<book genre="philosophy" publicationdate="1991-02-15">
<title>The Gorgias</title>
<author>
<name>Plato</name>
</author>
<price>9.99</price>
</book>
</bookstore>
使用XmlDocument类
读取节点
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");
XmlNodeList nodelst = doc.GetElementsByTagName("title");
foreach (XmlNode node in nodelst)
{
Console.WriteLine(node.OuterXml + "\r\n");
}
插入节点
XmlTextWriter的局限性是不能将节点插入到当前文档中,但是XmlDocument 可以做到
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");
XmlElement newBook = doc.CreateElement("book");
newBook.SetAttribute("genre", "mystry");
newBook.SetAttribute("publicationdate", "2005-01-01");
newBook.SetAttribute("ISBN", "0-201-6336-1-1");
XmlElement newTitle = doc.CreateElement("title");
newTitle.InnerText = "The Case of Mistry";
newBook.AppendChild(newTitle);
XmlElement newAuthor = doc.CreateElement("author");
newBook.AppendChild(newAuthor);
XmlElement newName = doc.CreateElement("name");
newName.InnerText = "Cook Monster";
newBook.AppendChild(newName);
XmlElement newProce = doc.CreateElement("price");
newProce.InnerText = "9.95";
newBook.AppendChild(newProce);
doc.DocumentElement.AppendChild(newBook);
//新建一个XmlTextWriter,把它传递给writecontentto方法,WriteContentTo把当前节点及所有子节点都保存在XmlTextWriter
XmlTextWriter tr = new XmlTextWriter("booksedit",null);
doc.WriteTo(tr);
tr.Close();
XPathNavigator类
XPathNavigator类包含移动和选择XML所需元素的所有方法。
1.创建:
a.如果是从XPathDocument中创建,则是只读的,只能浏览数据;
b.如果是从XmlDocument中创建,则可以编辑文档;
2.查询:使用Select()方法通过XPath语句查询;
3.迭代:使用XPathNodeIterator类,MoveNext()方法移动下一个节点;Current属性表示当前节点;
4.求值:使用Evaluate()方法计算表达式的值;
5.插入节点:先检查CanEdit属性是否为true,再使用InsertAfter()方法插入新节点。
//打印总价
XPathDocument doc=new XPathDocument("books.xml");
XPathNavigator nav = ((IXPathNavigable)doc).CreateNavigator();
Console.WriteLine( nav.Evaluate("sum(/bookstore/book/price)"));//计算总价
//
打印价格和总价
XPathDocument doc=new XPathDocument("books.xml");
XPathNavigator nav = ((IXPathNavigable)doc).CreateNavigator();
XPathNodeIterator iter = nav.Select("/bookstore/book");
while (iter.MoveNext())
{
XPathNodeIterator newIter = iter.Current.SelectDescendants(XPathNodeType.Element, false);
while (newIter.MoveNext())
{
if (newIter.Current.Name == "price")
{
Console.WriteLine(newIter.Current.Name + " : " + newIter.Current.Value);
}
}
}
Console.WriteLine( nav.Evaluate("sum(/bookstore/book/price)"));
//增加节点
XmlDocument doc=new XmlDocument();
doc.Load("books.xml");
XPathNavigator nav = ((IXPathNavigable)doc).CreateNavigator();
XPathNodeIterator iter = nav.Select("/bookstore/book/price");
if (nav.CanEdit)
{
while (iter.MoveNext())
{
iter.Current.InsertAfter("<disc>0.5</disc>");
}
doc.Save("NewBooks.xml");
}
//读到DataSet中
public DataSet getXML()
{
try
{
DataSet ds = new DataSet();
StreamReader sr = new StreamReader("books.xml", Encoding.Default);
ds.ReadXml(sr);
sr.Close();
if (ds.Tables.Count > 0)
return ds;
else
return null;
}
catch (Exception)
{
return null;
}
}
XDocument对象
XDocument替代了3.5之前的俄XmlDocument
XDocument xDoc = XDocument.Load("books.xml");
Console.WriteLine(xDoc.Root.Name.ToString());
Console.WriteLine(xDoc.Root.HasAttributes);
//输出:
bookstore
false
XElement:可以创建单个元素对象
XElement xe = new XElement("Company",new XAttribute("A","MyAttri"), new XElement("ComanyName", "Citi"), new XElement("CompanyAddress", new XElement("Address", "Main Street 123"), new XElement("Code", "454123")));
Console.WriteLine(xe.ToString());
XMLReader是一个抽象类,直接使用XMLReader必须使用静态方法Create,返回XMLReader对象
在读每个节点时,都要检查Nodetype属性,如果是文本就输出
XmlReader reader = XmlReader.Create("books.xml");
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Text)
{
Console.WriteLine(reader.Value+"\n\n");
}
}
ReadElementString
可以选择以元素名作为参数,只读取string类型。
示例中 如果节点类型不是element,或者名称不是title,就会调用reader()方法进入下一个节点。
在成功执行ReadElementString不需要调用reader方法,因为ReadElementString已经调用了整个Element,并定为到下一个节点
XmlReader reader2 = XmlReader.Create("books.xml");
while (!reader2.EOF)
{
if (reader2.MoveToContent() == XmlNodeType.Element && reader2.Name == "title")
{
Console.WriteLine(reader2.ReadElementString() + "\n\n");
}
else
{
reader2.Read();
}
}
如果去掉reader2.Name == "title",会出错因为MoveToContent检查到的第一个元素不包含文本类型
所以代码1可以变成
XmlReader reader2 = XmlReader.Create("books.xml");
while (!reader2.EOF)
{
if (reader2.MoveToContent() == XmlNodeType.Element )
{
try
{
Console.WriteLine(reader2.ReadElementString() + "\n\n");
}
catch (XmlException ex) { }//如果发生异常,就跳过
}
else
{
reader2.Read();
}
}
XMLReader类进行验证
可以使用XmlReaderSettings,根据XSD架构验证XML
XSD架构
去掉了XML中的一个必须节点ISBN,这样在验证时会抱错
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://www.test.com/books2" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="bookstore">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="book">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string" />
<xs:element name="author">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" name="name" type="xs:string" />
<xs:element minOccurs="0" name="first-name" type="xs:string" />
<xs:element minOccurs="0" name="last-name" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="price" type="xs:decimal" />
</xs:sequence>
<xs:attribute name="genre" type="xs:string" use="required" />
<xs:attribute name="publicationdate" type="xs:date" use="required" />
<xs:attribute name="ISBN" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
XML架构
<bookstore xmlns="http://www.test.com/books2">
<book genre="autobiography" publicationdate="1981-03-22" 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>
<book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
<title>The Confidence Man</title>
<author>
<first-name>Herman</first-name>
<last-name>Melville</last-name>
</author>
<price>11.99</price>
</book>
<book genre="philosophy" publicationdate="1991-02-15">
<title>The Gorgias</title>
<author>
<name>Plato</name>
</author>
<price>9.99</price>
</book>
</bookstore>
使用XmlDocument类
读取节点
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");
XmlNodeList nodelst = doc.GetElementsByTagName("title");
foreach (XmlNode node in nodelst)
{
Console.WriteLine(node.OuterXml + "\r\n");
}
插入节点
XmlTextWriter的局限性是不能将节点插入到当前文档中,但是XmlDocument 可以做到
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");
XmlElement newBook = doc.CreateElement("book");
newBook.SetAttribute("genre", "mystry");
newBook.SetAttribute("publicationdate", "2005-01-01");
newBook.SetAttribute("ISBN", "0-201-6336-1-1");
XmlElement newTitle = doc.CreateElement("title");
newTitle.InnerText = "The Case of Mistry";
newBook.AppendChild(newTitle);
XmlElement newAuthor = doc.CreateElement("author");
newBook.AppendChild(newAuthor);
XmlElement newName = doc.CreateElement("name");
newName.InnerText = "Cook Monster";
newBook.AppendChild(newName);
XmlElement newProce = doc.CreateElement("price");
newProce.InnerText = "9.95";
newBook.AppendChild(newProce);
doc.DocumentElement.AppendChild(newBook);
//新建一个XmlTextWriter,把它传递给writecontentto方法,WriteContentTo把当前节点及所有子节点都保存在XmlTextWriter
XmlTextWriter tr = new XmlTextWriter("booksedit",null);
doc.WriteTo(tr);
tr.Close();
XPathNavigator类
XPathNavigator类包含移动和选择XML所需元素的所有方法。
1.创建:
a.如果是从XPathDocument中创建,则是只读的,只能浏览数据;
b.如果是从XmlDocument中创建,则可以编辑文档;
2.查询:使用Select()方法通过XPath语句查询;
3.迭代:使用XPathNodeIterator类,MoveNext()方法移动下一个节点;Current属性表示当前节点;
4.求值:使用Evaluate()方法计算表达式的值;
5.插入节点:先检查CanEdit属性是否为true,再使用InsertAfter()方法插入新节点。
//打印总价
XPathDocument doc=new XPathDocument("books.xml");
XPathNavigator nav = ((IXPathNavigable)doc).CreateNavigator();
Console.WriteLine( nav.Evaluate("sum(/bookstore/book/price)"));//计算总价
//
打印价格和总价
XPathDocument doc=new XPathDocument("books.xml");
XPathNavigator nav = ((IXPathNavigable)doc).CreateNavigator();
XPathNodeIterator iter = nav.Select("/bookstore/book");
while (iter.MoveNext())
{
XPathNodeIterator newIter = iter.Current.SelectDescendants(XPathNodeType.Element, false);
while (newIter.MoveNext())
{
if (newIter.Current.Name == "price")
{
Console.WriteLine(newIter.Current.Name + " : " + newIter.Current.Value);
}
}
}
Console.WriteLine( nav.Evaluate("sum(/bookstore/book/price)"));
//增加节点
XmlDocument doc=new XmlDocument();
doc.Load("books.xml");
XPathNavigator nav = ((IXPathNavigable)doc).CreateNavigator();
XPathNodeIterator iter = nav.Select("/bookstore/book/price");
if (nav.CanEdit)
{
while (iter.MoveNext())
{
iter.Current.InsertAfter("<disc>0.5</disc>");
}
doc.Save("NewBooks.xml");
}
//读到DataSet中
public DataSet getXML()
{
try
{
DataSet ds = new DataSet();
StreamReader sr = new StreamReader("books.xml", Encoding.Default);
ds.ReadXml(sr);
sr.Close();
if (ds.Tables.Count > 0)
return ds;
else
return null;
}
catch (Exception)
{
return null;
}
}
XDocument对象
XDocument替代了3.5之前的俄XmlDocument
XDocument xDoc = XDocument.Load("books.xml");
Console.WriteLine(xDoc.Root.Name.ToString());
Console.WriteLine(xDoc.Root.HasAttributes);
//输出:
bookstore
false
XElement:可以创建单个元素对象
XElement xe = new XElement("Company",new XAttribute("A","MyAttri"), new XElement("ComanyName", "Citi"), new XElement("CompanyAddress", new XElement("Address", "Main Street 123"), new XElement("Code", "454123")));
Console.WriteLine(xe.ToString());