在.NET中使用XML
如果使用过MSXML3,那么在.NET应用程序中使用XML将是一个相当简单的过程。即时没有接触过MSXML3,也不要紧,你会发现使用.NET平台提供的相关类也是很容易的一件事情。
有两种主要API可用于访问建立在XML文档中的数据,它们包括只向前的无缓冲存取以及随机存取,而且自始至终都使用到文档对象模型DOM。有关这2个API的类位于System.XML集合中。
如果要快速有效地访问XML文档中的数据,就需要使用XmlTextReader类。这个类采取“拉”模式处理方式,要比简单XML API(SAX)中的“推”模式处理方式优越许多。使用XmlTextReader类之前首先要引用System.Xml集合,在C#中是使用“using”关键字来引用,在Visual Basic中则是使用“imports”关键字。引用了集合后,就可以象下面的代码所示开始例示读操作了:
XmlTextReader reader = new XmlTextReader(pathToXmlDoc);
int elementCount = 0;
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element) {
elementCount ;
}
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(pathToXmlDoc);
XmlNode root = xmlDoc.DocumentElement;
XmlDocument xmlDoc = new XmlDocument();
XmlDoc.Load(pathToXmlDoc);
XmlElement root = xmlDoc.DocumentElement;
XmlElement newNode = doc.CreateElement("newNode");
newNode.SetAttribute("id","1");
root.AppendChild(newNode);
<?xml version="1.0"?>
<root>
<newNode id="1"/>
</root>
string myXml = "<root><someNode>Hello</someNode></root>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(myXml);
//....manipulation or reading of the nodes can occur here
using System.Xml;
XmlTextReader reader = new XmlTextReader("C:\temp\xmltest.xml");
while ( reader.Read() )
{
Console.WriteLine(reader.Name);
}
namespace WriteToXML
{
using System;
using System.Xml;
/// <summary>
/// Summary description for Class1.
/// </summary>
public class Class1
{
public Class1()
{
}
public static int Main(string[] args)
{
try
{
XmlTextWriter writer = new XmlTextWriter("C:\temp\xmltest.xml", null);
writer.WriteStartDocument();
writer.WriteComment("Commentss: XmlWriter Test Program");
writer.WriteProcessingInstruction("Instruction","Person Record");
writer.WriteStartElement("p", "person", "urn:person");
writer.WriteStartElement("LastName","");
writer.WriteString("Chand");
writer.WriteEndElement();
writer.WriteStartElement("FirstName","");
writer.WriteString("Chand");
writer.WriteEndElement();
writer.WriteElementInt16("age","", 25);
writer.WriteEndDocument();
}
catch (Exception e)
{
Console.WriteLine ("Exception: {0}", e.ToString());
}
return 0;
}
}
}
using System.Xml;
XmlDocument doc = new XmlDocument();
doc.LoadXml("<XMLFile>"
" <SomeData>Old Data</SomeData>"
"</XMLFile>");
try
{
XmlNode currNode;
XmlDocument doc = new XmlDocument();
doc.LoadXml("<XMLFile>"
" <SomeData>Old Data</SomeData>"
"</XMLFile>");
XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
docFrag.InnerXml="<Inserted>"
" <NewData>Inserted Data</NewData>"
"</Inserted>";
// insert the availability node into the document
currNode = doc.DocumentElement.FirstChild;
currNode.InsertAfter(docFrag, currNode.LastChild);
//save the output to a file
doc.Save("InsertedDoc.xml");
}
catch (Exception e)
{
Console.WriteLine ("Exception: {0}", e.ToString());
}
- <XMLFile>
- <SomeData>
Old Data
- <Inserted>
<NewData>Inserted Data</NewData>
</Inserted>
</SomeData>
</XMLFile>