使用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);
}

处理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 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;
}
}

使用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
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
}

可选元素:

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();

读取特性attributes:

<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:

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();
}

写特性attributes:

writer.WriteStartElement ("customer");
writer.WriteAttributeString ("id", "1");
writer.WriteAttributeString ("status", "archived");

Namespaces and prefixes:

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();

使用分层数据:

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();
}
}
}

使用XmlReader和XElement:

XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true; using (XmlReader r = XmlReader.Create ("logfile.xml", settings))
{
r.ReadStartElement ("log");
while (r.Name == "logentry")
{
XElement logEntry = (XElement) XNode.ReadFrom (r);
int id = (int) logEntry.Attribute ("id");
DateTime date = (DateTime) logEntry.Element ("date");
string source = (string) logEntry.Element ("source");
...
}
r.ReadEndElement();
}

使用XmlWriter和XElement:

using (XmlWriter w = XmlWriter.Create ("log.xml"))
{
w.WriteStartElement ("log");
for (int i = 0; i < 1000000; i++)
{
XElement e = new XElement ("logentry",
new XAttribute ("id", i),
new XElement ("date", DateTime.Today.AddDays (-1)),
new XElement ("source", "test"));
e.WriteTo (w);
}
w.WriteEndElement();
}

创建一个XmlDocument:

XmlDocument doc = new XmlDocument();
doc.AppendChild (doc.CreateXmlDeclaration ("1.0", null, "yes")); XmlAttribute id = doc.CreateAttribute ("id");
XmlAttribute status = doc.CreateAttribute ("status");
id.Value = "123";
status.Value = "archived"; XmlElement firstname = doc.CreateElement ("firstname");
XmlElement lastname = doc.CreateElement ("lastname");
firstname.AppendChild (doc.CreateTextNode ("Jim"));
lastname.AppendChild (doc.CreateTextNode ("Bo")); XmlElement customer = doc.CreateElement ("customer");
customer.Attributes.Append (id);
customer.Attributes.Append (status);
customer.AppendChild (lastname);
customer.AppendChild (firstname); doc.AppendChild (customer);

XPath:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<customers>
<customer id="123" status="archived">
<firstname>Jim</firstname>
<lastname>Bo</lastname>
</customer>
<customer>
<firstname>Thomas</firstname>
<lastname>Jefferson</lastname>
</customer>
</customers>
XmlDocument doc = new XmlDocument();
doc.Load ("customers.xml");
XmlNode n = doc.SelectSingleNode ("customers/customer[firstname='Jim']");
Console.WriteLine (n.InnerText); // JimBo
XDocument doc = XDocument.Load (@"Customers.xml");
XElement e = e.XPathSelectElement ("customers/customer[firstname='Jim']");
Console.WriteLine (e.Value); // JimBo
XmlNode node1 = doc.SelectSingleNode ("customers");
XmlNode node2 = doc.SelectSingleNode ("customers/customer");
XmlNodeList nodes3 = doc.SelectNodes ("//lastname");
XmlNodeList nodes4 = doc.SelectNodes ("customers/customer..customers");
XmlNodeList nodes5 = doc.SelectNodes ("customers/customer/*");
XmlNode node6 = doc.SelectSingleNode ("customers/customer/@id");
XmlNode node7 = doc.SelectSingleNode ("customers/customer[firstname='Jim']");
XmlNode node8 = doc.SelectSingleNode ("x:customers");

XPathNavigator:

XPathNavigator nav = doc.CreateNavigator();
XPathNavigator jim = nav.SelectSingleNode
(
"customers/customer[firstname='Jim']"
); Console.WriteLine (jim.Value); // JimBo

使用Select:

XPathNavigator nav = doc.CreateNavigator();
string xPath = "customers/customer/firstname/text()";
foreach (XPathNavigator navC in nav.Select (xPath))
Console.WriteLine (navC.Value);

Compiling an XPath query:

XPathNavigator nav = doc.CreateNavigator();
XPathExpression expr = nav.Compile ("customers/customer/firstname");
foreach (XPathNavigator a in nav.Select (expr))
Console.WriteLine (a.Value);

命名空间查询:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>

<o:customers xmlns:o='http://oreilly.com'>
<o:customer id="123" status="archived">
<firstname>Jim</firstname>
<lastname>Bo</lastname>
</o:customer>
<o:customer>
<firstname>Thomas</firstname>
<lastname>Jefferson</lastname>
</o:customer>
</o:customers>
XmlDocument doc = new XmlDocument();
doc.Load ("customers.xml"); XmlNamespaceManager xnm = new XmlNamespaceManager (doc.NameTable);
xnm.AddNamespace ("o", "http://oreilly.com"); XmlNode n = doc.SelectSingleNode ("o:customers/o:customer", xnm);

XPathDocument:

XPathDocument doc = new XPathDocument ("customers.xml");
XPathNavigator nav = doc.CreateNavigator();
foreach (XPathNavigator a in nav.Select ("customers/customer/firstname"))
Console.WriteLine (a.Value);

XSD和schema验证:

<?xml version="1.0"?>
<customers>
<customer id="1" status="active">
<firstname>Jim</firstname>
<lastname>Bo</lastname>
</customer>
<customer id="1" status="archived">
<firstname>Thomas</firstname>
<lastname>Jefferson</lastname>
</customer>
</customers>
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified"
elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="customers">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="customer">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string" />
<xs:element name="lastname" type="xs:string" />
</xs:sequence>
<xs:attribute name="id" type="xs:int" use="required" />
<xs:attribute name="status" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

验证一个XmlReader:

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add (null, "customers.xsd"); using (XmlReader r = XmlReader.Create ("customers.xml", settings))
try { while (r.Read()) ; }
catch (XmlSchemaValidationException ex)
{
...
}

使用ValidationEventHandler:

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add (null, "customers.xsd");
settings.ValidationEventHandler += ValidationHandler; using (XmlReader r = XmlReader.Create ("customers.xml", settings))
while (r.Read()) ;
static void ValidationHandler (object sender, ValidationEventArgs e)
{
Console.WriteLine ("Error: " + e.Exception.Message);
}

验证一个X-DOM或者XmlDocument:

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add (null, "customers.xsd"); XDocument doc;
using (XmlReader r = XmlReader.Create ("customers.xml", settings))
try { doc = XDocument.Load (r); }
catch (XmlSchemaValidationException ex) { ... } XmlDocument xmlDoc = new XmlDocument();
using (XmlReader r = XmlReader.Create ("customers.xml", settings))
try { xmlDoc.Load (r); }
catch (XmlSchemaValidationException ex) { ... }
XDocument doc = XDocument.Load (@"customers.xml");
XmlSchemaSet set = new XmlSchemaSet();
set.Add (null, @"customers.xsd");
StringBuilder errors = new StringBuilder();
doc.Validate (set, (sender, args) => { errors.AppendLine
(args.Exception.Message); }
);
Console.WriteLine (errors.ToString());

XSLT:

<customer>
<firstname>Jim</firstname>
<lastname>Bo</lastname>
</customer>
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<html>
<p><xsl:value-of select="//firstname"/></p>
<p><xsl:value-of select="//lastname"/></p>
</html>
</xsl:template>
</xsl:stylesheet>
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load ("test.xslt");
transform.Transform ("input.xml", "output.xml");

C# 3.0 其他XML技术的更多相关文章

  1. C# XML技术总结之XDocument 和XmlDocument

    引言 虽然现在Json在我们的数据交换中越来越成熟,但XML格式的数据还有很重要的地位. C#中对XML的处理也不断优化,那么我们如何选择XML的这几款处理类 XmlReader,XDocument ...

  2. 打造完美的xml技术解决方案(dom4j/xstream)

    转: XML 技术是随着 Java 的发展而发展起来的.在 XML 出现之前对于简单的数据格式通常是存储在 ini 配置文件等文本文件中,复杂的格式则采用自定义的文件格式,因此对于每种文件格式都要有专 ...

  3. xml技术DTD约束定义

    XML约束 在XML技术中,可以编写一个文档来约束一个xml文档的书写规范,这称之为XML约束为什么需要XML约束? class.xml <stu><面积>?人怎么会有面积元素 ...

  4. 【Java】Java XML 技术专题

    XML 基础教程 XML 和 Java 技术 Java XML文档模型 JAXP(Java API for XML Parsing) StAX(Streaming API for XML) XJ(XM ...

  5. JavaEE:Eclipse开发工具的相关使用和XML技术

    Eclipse开发工具的知识点1.工程的属性(properties)1)Text file encoding  工程编码(在导入其他工程时,注意编码类型一致)2)Java build path设置cl ...

  6. XML技术思想

    百科名片: 可扩展标记语言 (Extensible Markup Language, XML) ,用于标记电子文件使其具有结构性的标记语言,可以用来标记数据.定义数据类型,是一种允许用户对自己的标记语 ...

  7. 14.PHP_PHP与XML技术

    PHP与XML技术 先把概念粘过来: 先来个基本模板: <?xml version="1.0" encoding="gb2312" standalone= ...

  8. XML技术的应用

    XML技术的发展历史:gml--->sml--->html--->xml(可扩展标记语言). HTML和XML技术的区别: 1.HTML技术的标签不能自己定义,必须使用规定语法编写: ...

  9. Django2.0+小程序技术打造微信小程序助手✍✍✍

    Django2.0+小程序技术打造微信小程序助手  整个课程都看完了,这个课程的分享可以往下看,下面有链接,之前做java开发也做了一些年头,也分享下自己看这个视频的感受,单论单个知识点课程本身没问题 ...

随机推荐

  1. SRM 596 DIV 2

    前段时间终于配置好了TopCoder的环境,所以就拿这场的DIV2练习了一下 1. 250pt FoxAndSightseeing 题意 给你n个城市的位置,他们在同一直线上,要求你跳过其中某一个城市 ...

  2. SignalTap II逻辑分析仪的使用

    一.例子 我们使用如图1所示的verilog代码所实现的开关电路作为例子.这个电路把DE系列开发板上的前8个开关简单的和对应的8个红色LED相连接.它是这样工作的:在时钟(CLOCK_50)的上升沿读 ...

  3. 数学之路(3)-机器学习(3)-机器学习算法-SVM[5]

    svm小结 1.超平面 两种颜色的点分别代表两个类别,红颜色的线表示一个可行的超平面.在进行分类的时候,我们将数据点  x 代入  f(x)  中,如果得到的结果小于 0 ,则赋予其类别 -1 ,如果 ...

  4. Chapter 1 Securing Your Server and Network(11):使用透明数据库加密

    原文出处:http://blog.csdn.net/dba_huangzj/article/details/38398813,专题文件夹:http://blog.csdn.net/dba_huangz ...

  5. 【24】若所有参数皆需类型转换,请为此采用non-members函数

    1.令class支持隐式类型转换,往往是个糟糕的主意.但有些情况是合理的,比如数值类型.考虑,有理数Rational有分子,分母两个字段,缺省参数值为0,1.Ration a = 2;我们期望构造一个 ...

  6. 查看Linux主机CPU及内存信息

    查看CPU信息(型号)  # cat /proc/cpuinfo | grep name | cut -f2 -d: | uniq -c        8  Intel(R) Xeon(R) CPU ...

  7. [Practical Git] Format commit history with git log arguments

    When running the git log command, we can pass in options as arguments toformat the data shown for ea ...

  8. Android开发心得(转)

    前言: 很早以前,就听人说过android以后会火起来,作为一个前瞻性对它有所了解会是一个转型的好机会,javaweb太成熟饱和了,现在市面上各种android手机层出不穷,网上各种android视频 ...

  9. android129 zhihuibeijing 聊天机器人

    上屏幕界面activity_main.xml: 语音识别界面 <LinearLayout xmlns:android="http://schemas.android.com/apk/r ...

  10. IDispatch接口介绍

    1.         C程序调用时,调用者必须预先知道接口规范(如,参数类型.参数字节长度.参数顺序等).由于不同语言这些规范有所不同,COM未解决不同语言之间调用,提供了IDispatch接口. 2 ...