XmlTextReader

作者:追风剑情 发布于:2016-12-26 16:32 分类:C#

示例一


  1. using System;
  2. using System.IO;
  3. using System.Xml;
  4.  
  5. namespace TestXML
  6. {
  7. class Program
  8. {
  9. private const String filename = "items.xml";
  10.  
  11. static void Main(string[] args)
  12. {
  13. PrintXml();
  14. Console.Read();
  15. }
  16.  
  17. public static void PrintXml()
  18. {
  19. XmlTextReader reader = null;
  20.  
  21. try
  22. {
  23. //读取xml文件
  24. reader = new XmlTextReader(filename);
  25. //忽略空白节点
  26. reader.WhitespaceHandling = WhitespaceHandling.None;
  27.  
  28. //遍历显示所有节点
  29. while (reader.Read())
  30. {
  31. switch (reader.NodeType)
  32. {
  33. case XmlNodeType.Element:
  34. Console.WriteLine("<{0}>", reader.Name);
  35. Console.WriteLine("ver="+reader.GetAttribute("ver"));//读取属性
  36. break;
  37. case XmlNodeType.Text:
  38. Console.WriteLine(reader.Value);
  39. break;
  40. case XmlNodeType.CDATA:
  41. Console.WriteLine("<![CDATA[{0}]]>", reader.Value);
  42. break;
  43. case XmlNodeType.ProcessingInstruction:
  44. Console.WriteLine("<?{0} {1}?>", reader.Name, reader.Value);
  45. break;
  46. case XmlNodeType.Comment:
  47. Console.WriteLine("<!--{0}-->", reader.Value);
  48. break;
  49. case XmlNodeType.XmlDeclaration:
  50. Console.WriteLine("<?xml version='1.0'?>");
  51. break;
  52. case XmlNodeType.Document:
  53. break;
  54. case XmlNodeType.DocumentType:
  55. Console.WriteLine("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value);
  56. break;
  57. case XmlNodeType.EntityReference:
  58. Console.WriteLine(reader.Name);
  59. break;
  60. case XmlNodeType.EndElement:
  61. Console.WriteLine("</{0}>", reader.Name);
  62. break;
  63. }
  64. }
  65. }
  66. finally
  67. {
  68. if (reader != null)
  69. reader.Close();
  70. }
  71. }
  72. }
  73. }


  1. <?xml version="1.0"?>
  2. <!-- This is a sample XML document -->
  3. <!DOCTYPE Items [<!ENTITY number "123">]>
  4. <Items>
  5. <Item ver="1.2">Test with an entity: &number;</Item>
  6. <Item ver="1.2">test with a child element <more/> stuff</Item>
  7. <Item ver="1.2">test with a CDATA section <![CDATA[<456>]]> def</Item>
  8. <Item ver="1.2">Test with an char entity: &#65;</Item>
  9. <!-- Fourteen chars in this element.-->
  10. <Item ver="1.2">1234567890ABCD</Item>
  11. </Items>

运行测试

11111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号