Xml Tips

Xml Tips

//z 2012-3-7 16:43:47 PM IS2120@CSDN

1. xml 中的注释

<!-- 这是注释 -->

并非用于 XML 分析器的内容(例如与文档结构或编辑有关的说明)可以包含在注释中。注释以 <!-- 开头,以 --> 结尾,例如<!--catalog last updated 2000-11-01-->

注释可以出现在文档序言中,包括文档类型定义 (DTD);文档之后;或文本内容中。注释不能出现在属性值中。不能出现在标记中。

分析器在遇到 > 时,就认为注释已结束;然后继续将文档作为正常的 XML 处理。因此,字符串 > 不能出现在注释中。除了该限制之外,任何合法的 XML 字符均可以出现在注释中,与 CDATA 节非常类似。这样,可以从分析器看到的输出流中删除 XML 注释,同时又不会删除文档的内容。

以下注释可以用于暂时除去标记。

<!--- <test pattern="SECAM" /><test pattern="NTSC" /> -->
注意//z 2012-3-7 16:43:47 PM IS2120@CSDN

在 HTML 中,可以使用注释来隐藏脚本和样式表。要在 XML 中使用此方法,可能必须检索注释,提取注释的内容,检查是否有标记字符,然后再进行重新分析。在此例中,CDATA 节是更好的选择。


2. 验证 xml 的合法性
??感觉不合适
public class MyXmlDocument: XmlDocument
{
  bool TryParseXml(string xml){
    try{
      ParseXml(xml);
      return true;
    }catch(XmlException e){
      return false;
    }
 }
Using a XmlValidatingReader will prevent the exceptions, if you provide your own ValidationEventHandler.


using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;

class XPathValidation
{
    static void Main()
    {
        try
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.Schemas.Add("http://www.contoso.com/books""contosoBooks.xsd");
            settings.ValidationType = ValidationType.Schema;

            XmlReader reader = XmlReader.Create("contosoBooks.xml", settings);
            XmlDocument document = new XmlDocument();
            document.Load(reader);

            ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);

            // the following call to Validate succeeds.
            document.Validate(eventHandler);

            // add a node so that the document is no longer valid
            XPathNavigator navigator = document.CreateNavigator();
            navigator.MoveToFollowing("price""http://www.contoso.com/books");
            XmlWriter writer = navigator.InsertAfter();
            writer.WriteStartElement("anotherNode""http://www.contoso.com/books");
            writer.WriteEndElement();
            writer.Close();

            // the document will now fail to successfully validate
            document.Validate(eventHandler);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    static void ValidationEventHandler(object sender, ValidationEventArgs e)
    {
        switch (e.Severity)
        {
            case XmlSeverityType.Error:
                Console.WriteLine("Error: {0}", e.Message);
                break;
            case XmlSeverityType.Warning:
                Console.WriteLine("Warning {0}", e.Message);
                break;
        }

    }
}

原文地址:https://www.cnblogs.com/IS2120/p/6745931.html