XML知识总结(C#和.NET2.0实战学习笔记)
1、 XML的元素的属性也可包括数据:
2、 使用<!---title-à插入注释
3、 XSD schema类型化XML文档及数据
4、 Xpath,相当于XML的sql语句
5、 XSLT样式表 是一种允许使用xml文档中的数据区生成新文档的语言,输出的文档可以是HTML,XML文档或任何简单的文本文档。
6、 XQuery目标与XSLT的目标是一样的。即把XML文档转换成另一文本文档。输出文档不一定是XML文档。这一功能看作是一种对XML文档进行查询操作的方法,因而得名XQuery,.net2.0并不支持XQuery1.0,但sql server2005支持使用Xquery的一个子集查询数据库中的XML数据
7、 使用XMLReader读取XML数据的一个实例:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace ConsoleApplication1
{
classProgram
{
staticvoid
{
XmlReaderxtr = XmlReader.Create(@"C:\books.xml");
stringsIndent = string.Empty;
stringsElem = string.Empty;
while(xtr.Read())
{
if (xtr.NodeType == XmlNodeType.Element)
{
sIndent = string.Empty;
for (int i = 0; i< xtr.Depth; i++) sIndent += " ";
sElem =xtr.Name;
if (xtr.MoveToFirstAttribute())
do
Console.WriteLine("{0}{1}Attr:{2}",
sIndent, sElem, xtr.Value);
while (xtr.MoveToNextAttribute());
}
else if (xtr.NodeType== XmlNodeType.Text)
Console.WriteLine("{0}{1}Val:{2}", sIndent, sElem, xtr.Value);
}
}
}
}
8、 使用XMLWriter类编辑数据
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Schema;
namespace ConsoleApplication1
{
classProgram
{
staticvoid
{
XmlTextWriterxtw = new XmlTextWriter(@"C:\book2.xml", Encoding.UTF8);
xtw.Formatting = Formatting.Indented;
xtw.WriteStartDocument(true);
xtw.WriteStartElement("books");
xtw.WriteStartElement("book");
xtw.WriteAttributeString("ISBN", "10-097661322-0");
xtw.WriteElementString("title", "Pratical.NET and C#");
xtw.WriteEndElement();
xtw.WriteEndElement();
xtw.WriteEndDocument();
xtw.Flush();
xtw.Close();
}
}
}
9、 使用XmlDocument类装载和遍历XML文档到内存中
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Schema;
namespace ConsoleApplication1
{
publicclass Program
{
staticvoid DisplayNode(XmlNodexNode, string sIndent)
{
Console.WriteLine("{0}Node: {1}({2})",
sIndent, xNode.Name, xNode.Value);
if(xNode.Attributes != null)
foreach (XmlAttributexAtt in xNode.Attributes)
Console.WriteLine("{0}Attribute: {1}", sIndent, xAtt.Value);
if(xNode.HasChildNodes)
foreach (XmlNode_xNode in xNode.ChildNodes)
DisplayNode(_xNode, sIndent + " ");
}
staticpublic void
{
XmlDocumentxDoc = new XmlDocument();
try{ xDoc.Load(@"C:\books.xml"); }
catch{ }
foreach(XmlNode xNode inxDoc.ChildNodes)
DisplayNode(xNode, string.Empty);
}
}
}
10、 使用XMLDOCUMENT类验证XML文档
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
public class Program {
staticpublic void
XmlDocument xDoc = new XmlDocument();
try{ xDoc.Load(@"C:\books.xml"); } catch { }
xDoc.Schemas.Add( string.Empty,@"C:\books.xsd");
xDoc.Schemas.Compile();
ValidationEventHandlervalidator = ValidatingProblemHandler;
xDoc.Validate(validator);
}
staticvoid ValidatingProblemHandler(object sender,
ValidationEventArgse) {
if(e.Severity == XmlSeverityType.Warning) {
Console.Write("WARNING: "); Console.WriteLine(e.Message);
} elseif (e.Severity == XmlSeverityType.Error) {
Console.Write("ERROR: "); Console.WriteLine(e.Message);
}
}
}
11、使用XPath遍历和编辑XML文档
对内存中的DOM树(通过XmlDocument载入到内存中)应用Xpath表达式
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Schema;
namespace ConsoleApplication1
{
publicclass Program
{
staticpublic void
{
XmlDocumentxDoc = new XmlDocument();
try{ xDoc.Load(@"C:\books.xml"); }
catch{ }
XmlNodeListbooks = xDoc.SelectNodes(
@"/bookstore/book/author/first-name");
foreach(XmlNode book inbooks)
System.Console.WriteLine(book.OuterXml);
}
}
}
12、 使用XPathNavigator实例来递归遍历用XpathDocument实例装载的XML文档
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
namespace ConsoleApplication1
{
classProgram
{
staticvoid
{
XPathDocumentdoc = new XPathDocument(@"C:\books.xml");
XPathNavigatornavigator = doc.CreateNavigator();
navigator.MoveToRoot();
DisplayRecursive(navigator, string.Empty);
}
static public voidDisplayRecursive(XPathNavigator navigator,
string indent)
{
if(navigator.HasChildren)
{
navigator.MoveToFirstChild();
DisplayNode(navigator,indent + " ");
DisplayRecursive(navigator, indent + " ");
navigator.MoveToParent();
}
while(navigator.MoveToNext())
{
DisplayNode(navigator, indent);
DisplayRecursive(navigator,indent);
}
}
staticprivate voidDisplayNode(XPathNavigator navigator, string indent)
{
if(navigator.NodeType == XPathNodeType.Text)
Console.WriteLine(indent + navigator.Value);
elseif (navigator.Name != String.Empty)
Console.WriteLine(indent + "<" + navigator.Name + ">");
}
}
}
13、 使用XpathNodeIterator对象遍历Xpath的选择结果集
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
namespace ConsoleApplication1
{
classProgram
{
staticvoid
{
XPathDocumentdocument = new XPathDocument(@"C:\books.xml");
XPathNavigatornavigator = document.CreateNavigator();
XPathNodeIteratoriterator =
navigator.Select(@"/bookstore/book/author/first-name");
while(iterator.MoveNext())
System.Console.WriteLine("<"+ iterator.Current.Name + ">" +
iterator.Current.Value);
}
}
}
14、 用XpathNavigator对象编辑XmlDocument对象
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
namespace ConsoleApplication1
{
classProgram
{
staticvoid
{
XmlDocumentxDoc = new XmlDocument();
try{ xDoc.Load(@"C:\books.xml"); }
catch{ }
XPathNavigatornavigator = xDoc.CreateNavigator();
navigator.MoveToRoot(); // Select the root.
if(navigator.MoveToFirstChild()) // Select <bookstore>.
if (navigator.MoveToFirstChild()) // Select
// <book>Autobiography...
navigator.InsertElementBefore(string.Empty,"book",
string.Empty, "Pratical.NET and C#");
xDoc.Save(@"C:\new_books.xml");
}
}
}
15、 使用XSLT样式表转换XML文档
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Xsl;
namespace ConsoleApplication1
{
classProgram
{
staticvoid
{
System.Xml.XmlDocument xDoc = newSystem.Xml.XmlDocument();
xDoc.Load(@"C:\books.xml");
XslCompiledTransformxTrans = new XslCompiledTransform();
xTrans.Load(@"C:\books.xsl");
xTrans.Transform(xDoc, null, System.Console.Out);
}
}
}
16、 使用dataset.writexml输出内存中数据集至xml文档中,连接关系型数据与XML文档的桥接器
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Xsl;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
classProgram
{
staticvoid
{
stringsCnx =
"server = localhost ; uid=sa ; pwd =000000; database= ORGANIZATION";
using(SqlConnection cnx = new SqlConnection(sCnx))
{
using (SqlDataAdapterdataAdapter = new SqlDataAdapter())
{
DataSet dataSet = newDataSet();
string sCmd = "SELECT* FROM EMPLOYEES";
dataAdapter.SelectCommand = new SqlCommand(sCmd, cnx);
dataAdapter.Fill(dataSet, "EMPLOYEES");
dataSet.WriteXml(@"C:\test.xml");
System.Console.WriteLine("-----------------------------");
dataSet.WriteXmlSchema(@"C:\test.xsd");
} // end using SqlDataAdapter
} // end using SqlConnection
}
}
}
17、 使用XML文档填充Dataset
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Xsl;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
classProgram
{
staticvoid
{
stringsCnx =
"server = localhost ; uid=sa ; pwd =000000; database= ORGANIZATION";
using(SqlConnection cnx = new SqlConnection(sCnx))
{
using (SqlDataAdapterdataAdapter = new SqlDataAdapter())
{
DataSet dataSet = newDataSet();
// Build automatically commands for updates.
string sCmd = "SELECT* FROM EMPLOYEES WHERE EmployeeID=-1";
dataAdapter.SelectCommand= new SqlCommand(sCmd,cnx);
SqlCommandBuilder cmdBuilder =
new SqlCommandBuilder(dataAdapter);
// Build the EMPLOYEES table and insert lines from
// the dataFile.xml file.
dataSet.ReadXml(@"C:/DataFile.xml");
// Update the database.
dataAdapter.Update(dataSet, "EMPLOYEES");
} // end using SqlDataAdapter
} // end using SqlConnection
}
}
}
18、 关于System.Xml.XmlDataDocument类
XML数据和Dataset可以相互转换,System.Xml.XmlDataDocument类(继承自XmlDocument)专门用于完成这一任务,为做到这点,我们必须把XmlDataDocument的实例绑定到Dataset,然后通过XmlDataDocument或者Dataset来操作数据。必须了解的是,他们在内部操作的是同一份数据。通过Dataset所做的修改会马上在XmlDataDocument上显现,反之亦然。
19、 XML和SQL Server
ADO.Net的SqlClient数据提供程序允许使用SQLXML。
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Xsl;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
namespace ConsoleApplication1
{
classProgram
{
staticvoid
{
stringsCnx =
"server = localhost ; uid=sa ; pwd =; database =ORGANIZATION";
stringsCmd = "SELECT * FROM EMPLOYEES FOR XMLAUTO";
using(DbConnection cnx = newSqlConnection(sCnx))
{
using (SqlCommandcmd = new SqlCommand(sCmd,
cnx as SqlConnection))
{
cnx.Open();
System.Xml.XmlReader reader = cmd.ExecuteXmlReader();
while (reader.Read())
System.Console.WriteLine(reader.ReadOuterXml());
reader.Close();
} // end usingcmd.
} // end using cnx.
System.Console.Read();
}
}
20、连接对象与XML文档的桥梁----SYSTEM.Xml.XmlSeriallization类
有了System.Xml.XmlSeriallization类,你可以把几乎所有的.net对象序列化成XML。序列化机制有几个局限:
A、 之序列化公共字段和属性
B、 不考虑[SerialZable]attribute和ISerialzable接口
C、 如果对象图存在至少一个循环引用,XmlSeriallizer无法序列化该对象图
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
publicclass book
{
publicstring genre { get{ return m_genre; } set{ m_genre = value; } }
privatestring m_genre;
publicstring title { get{ return m_title; } set{ m_title = value; } }
privatestring m_title;
publicdecimal price { get{ return m_price; } set{ m_price = value; } }
privatedecimal m_price;
}
publicclass Program
{
staticpublic void
{
bookb1 = new book();
b1.genre = "autobiography";
b1.title = "The Autobiography of Benjamin Franklin";
b1.price =
//Store the state of an instance of the 鈥榖ook鈥?class ...
//... in the 鈥榖ook.xml鈥?file.
FileStreamfs1 = File.OpenWrite("book.xml");
XmlSerializerxmls = new XmlSerializer(typeof(book));
xmls.Serialize(fs1, b1);
fs1.Close();
//Create an instance of the 鈥榖ook鈥?class ...
//... from the 鈥榖ook.xml鈥?file.
FileStreamfs2 = File.OpenRead("book.xml");
bookb2 = (book)xmls.Deserialize(fs2);
fs2.Close();
}
}
}
21、用于XML序列化的attribute
XmlRoot指定类或者结构作为根结点
XmlElement指定类的公共字段或属性序列化成Xml元素
XmlAttribute指定类的公共字段或属性序列化成XML属性而不是XML元素
XmlArrayItem指定类的实例可以被序列化到数组中
XmlIgnore指示不被序列化的公共字段或属性
22、Sgen.exe的用法(?)
23、Xsd.exe的用法(?)