System.Xml FAQ Part 1

   作为一项单独的任务,最近XML小组收到一个问题列表。我们觉得这个列表很有借鉴意义,因为许多用户遇到的困难都是它们导致的。这些问题既有冷僻方法的调用,也有复杂XML的构建,但是我们将注意力集中在了一些真正难以调试的场景。当完成这个任务以后,我们想,应该把它们公布出来。

  

Q1: 特殊字符   

        有一些特殊字符作为保留字不能在XML中使用,比如"&"、“<”。XML标准有三种方法可以解决这个问题:转义字符、实体参考、CDATA .

        OK,这个问题对于有经验的用户来说,像是基本的XML101,但是对于新用户来说可能就是一个噩梦。问题之所以复杂化了,是因为XML 解析器通常返回令人迷惑的错误信息。这个错误也是新用户经常遇到的,因为通常待使用的文本往往包含这些特殊字符。这些字符是:

  • &   (&amp;)
  • <    (&lt;)
  • >    (&gt;)
  • ‘    (&apos;)
  • “   (&quot;)

下面是几个包含了这些特殊字符的字符串,以及相应的异常信息。这些异常都包含行号和列号,可以辅助你找到错误。

 

Character String

Correct Usage

Exception Message

A & B

A &amp; B

An error occurred while parsing EntityName. Line X, position Y.  

A &c B

A &amp;c B

' ' is an unexpected token. The expected token is ';'. Line X, position Y.

A &# B

A &amp;# B

Invalid syntax for a decimal numeric entity reference. Line X, position Y.

A < B

A &lt; B

Name cannot begin with the ' ' character, hexadecimal value 0x20. Line X, position Y.

 

Q2: XML 片段

有时候你可能需要解析一些不符合标准的XML片段,比如一个没有根节点的XML字符串,例如:

“<foo></foo><bar></bar>”

如果你把这个XML片段当做XmlReader的参数,你会得到一个异常:

“There are multiple root elements. Line X, position Y.”

这个异常设计的非常好,它准确说明了发生的错误:一个XML文档只能有一个根节点。但是如果你真的想解析这类XML该怎么做呢?看下面的代码:

string xmlFragmentStr = "<foo></foo><bar></bar>";
//create a reader settings objects and set the conformance level to

fragment
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.ConformanceLevel = ConformanceLevel.Fragment;
//create a reader using the reader settings
XmlReader r = XmlReader.Create(new StringReader(xmlFragmentStr),

xrs);
r.Read();

 

PS One:

Some future FAQ post topics include but are not limited to:

-          Reporting Validation Warnings

-          Correct Encodings

-          ProhibitDTD setting

-          XLinq Bridge Classes

 

PS Two:

不知道大家有没有人对校内网感兴趣。校内网上的应用 现在也有很多很多了。小弟最近想做一个LINQ TO XiaoNei,就是一个Linq Provider,可以让开发者用C# Linq feature,操作校内网数据(用户,朋友,通知之类的)。正在恶补XML。。。。

 

posted @ 2008-10-28 17:36  心利  阅读(2177)  评论(1编辑  收藏  举报
SharePoint Add-ons