URI:http://www.albahari.com/nutshell/cs4ch11.aspx
Enumerating nodes with XmlReader
使用XmlReader阅读器来对节点进行枚举读取
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<customer id="123" status="archived">
<firstname>Jim</firstname>
<lastname>Bo</lastname>
</customer>
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
using (XmlReader reader = XmlReader.Create ("customer.xml", settings))
while (reader.Read())
{
Console.Write (new string (' ',reader.Depth*2)); // Write indentation
Console.WriteLine (reader.NodeType);
}
Processing XNodeType
处理多种类型的节点
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE customer [ <!ENTITY tc "Top Customer"> ]>
<customer id="123" status="archived">
<firstname>Jim</firstname>
<lastname>Bo</lastname>
<quote><![CDATA[C#'s operators include: < > &]]></quote>
<notes>Jim Bo is a &tc;</notes>
<!-- That wasn't so bad! -->
</customer>
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
settings.ProhibitDtd = false; // Must set this to read DTDs 必须要将该XML阅读器对象设置为允许读取DTD的数据
using (XmlReader r = XmlReader.Create ("customer.xml", settings))
while (r.Read())
{
Console.Write (r.NodeType.ToString().PadRight (17, '-'));
Console.Write ("> ".PadRight (r.Depth * 3));
switch (r.NodeType)
{
case XmlNodeType.Element:
case XmlNodeType.EndElement:
Console.WriteLine (r.Name); break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Comment:
case XmlNodeType.XmlDeclaration:
Console.WriteLine (r.Value); break;
case XmlNodeType.DocumentType:
Console.WriteLine (r.Name + " - " + r.Value); break;
default: break;
}
}
Using ReadElementContentAs
读取节点元素内容用例如:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<customer id="123" status="archived">
<firstname>Jim</firstname>
<lastname>Bo</lastname>
<creditlimit>500.00</creditlimit> <!-- OK, we sneaked this in! -->
</customer>
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
using (XmlReader r = XmlReader.Create ("customer.xml", settings))
{
r.MoveToContent(); // Skip over the XML declaration 这里跳过XML的定义
r.ReadStartElement ("customer");
string firstName = r.ReadElementContentAsString ("firstname", "");
string lastName = r.ReadElementContentAsString ("lastname", "");
decimal creditLimit = r.ReadElementContentAsDecimal ("creditlimit", "");
r.MoveToContent(); // Skip over that pesky comment 这里跳过一些不相关本次操作的描述
r.ReadEndElement(); // Read the closing customer tag 将XML阅读器的指针推到当前XML文档的最后关闭标签:</customer>
}
Optional elements:
选择节点元素
r.ReadStartElement ("customer");
string firstName = r. ReadElementContentAsString ("firstname", "");
string lastName = r.Name == "lastname"
? r.ReadElementContentAsString() : null;
decimal creditLimit = r.ReadElementContentAsDecimal ("creditlimit", "");
Checking for an empty element:
检查空的节点元素:
bool isEmpty = reader.IsEmptyElement;
reader.ReadStartElement ("customerList");
if (!isEmpty) reader.ReadEndElement();
Reading attributes:
读取XML文档指定节点元素的特性
<customer id="123" status="archived"/>
Console.WriteLine (reader ["id"]); // 123
Console.WriteLine (reader ["status"]); // archived
Console.WriteLine (reader ["bogus"] == null); // True
Console.WriteLine (reader [0]); // 123
Console.WriteLine (reader [1]); // archived
reader.MoveToAttribute ("status");
string status = ReadContentAsString();
reader.MoveToAttribute ("id");
int id = ReadContentAsInt();
if (reader.MoveToFirstAttribute())
do
{
Console.WriteLine (reader.Name + "=" + reader.Value);
}
while (reader.MoveToNextAttribute());
// OUTPUT:
id=123
status=archived
XmlWriter:
使用XmlWriter的XML写入器:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create ("..\\..\\foo.xml", settings))
{
writer.WriteStartElement ("customer");
writer.WriteElementString ("firstname", "Jim");
writer.WriteElementString ("lastname"," Bo");
writer.WriteEndElement();
}
Writing attributes:
向写入指定节点元素的特性:
writer.WriteStartElement ("customer");
writer.WriteAttributeString ("id", "1");
writer.WriteAttributeString ("status", "archived");
Namespaces and prefixes:
使用XML写入器向XML文档写入节点的命名空间与前缀:
writer.WriteStartElement ("o", "customer", "http://oreilly.com");
writer.WriteElementString ("o", "firstname", "http://oreilly.com", "Jim");
writer.WriteElementString ("o", "firstname", "http://oreilly.com", "Bo");
writer.WriteEndElement();
Working with hierarchical data:
分开处理XML数据的例子:
public class Customer
{
public const string XmlName = "customer";
public int? ID;
public string FirstName, LastName;
public Customer() { }
public Customer (XmlReader r) { ReadXml (r); }
public void ReadXml (XmlReader r)
{
if (r.MoveToAttribute ("id")) ID = r.ReadContentAsInt();
r.ReadStartElement();
FirstName = r.ReadElementContentAsString ("firstname", "");
LastName = r.ReadElementContentAsString ("lastname", "");
r.ReadEndElement();
}
public void WriteXml (XmlWriter w)
{
if (ID.HasValue) w.WriteAttributeString ("id", "", ID.ToString());
w.WriteElementString ("firstname", FirstName);
w.WriteElementString ("lastname", LastName);
}
}
public class Supplier
{
public const string XmlName = "supplier";
public string Name;
public Supplier() { }
public Supplier (XmlReader r) { ReadXml (r); }
public void ReadXml (XmlReader r)
{
r.ReadStartElement();
Name = r.ReadElementContentAsString ("name", "");
r.ReadEndElement();
}
public void WriteXml (XmlWriter w)
{
w.WriteElementString ("name", Name);
}
}
public class Contacts
{
public IList<Customer> Customers = new List<Customer>();
public IList<Supplier> Suppliers = new List<Supplier>();
public void ReadXml (XmlReader r)
{
bool isEmpty = r.IsEmptyElement; // This ensures we don't get 确保我们不操作空节点元素的文档
r.ReadStartElement(); // snookered by an empty 该方法内部会阻止读取空的节点元素
if (isEmpty) return; // <contacts/> element!
while (r.NodeType == XmlNodeType.Element)
{
if (r.Name == Customer.XmlName) Customers.Add (new Customer (r));
else if (r.Name == Supplier.XmlName) Suppliers.Add (new Supplier (r));
else
throw new XmlException ("Unexpected node: " + r.Name);
}
r.ReadEndElement();
}
public void WriteXml (XmlWriter w)
{
foreach (Customer c in Customers)
{
w.WriteStartElement (Customer.XmlName);
c.WriteXml (w);
w.WriteEndElement();
}
foreach (Supplier s in Suppliers)
{
w.WriteStartElement (Supplier.XmlName);
s.WriteXml (w);
w.WriteEndElement();
}
}
}
(未完)