XmlDocument

作者:追风剑情 发布于:2019-7-1 22:09 分类:C#

示例:

test.xml


  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <root>
  3. <book name="《三国演义》">内容摘要</book>
  4. <book name="《水浒专》">内容摘要</book>
  5. </root>


代码


  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Xml;
  6.  
  7. namespace XmlTest
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. ParseXML("test.xml");
  14.  
  15. Console.ReadKey();
  16. }
  17.  
  18. private static void ParseXML(string path)
  19. {
  20. XmlDocument xml = new XmlDocument();
  21. xml.Load(path);
  22.  
  23. //选择根节点
  24. XmlNode root = xml.SelectSingleNode("/root");
  25. //获取所有子节点
  26. XmlNodeList childList = root.ChildNodes;
  27.  
  28. for (int i=0; i<childList.Count; i++)
  29. {
  30. XmlNode node = childList.Item(i);
  31. if (node.NodeType == XmlNodeType.Comment) //跳过XML中的注释
  32. continue;
  33. Console.WriteLine("节点名称:" + node.Name);
  34. Console.WriteLine("节点类型:" + node.NodeType.ToString());
  35. Console.WriteLine("LocalName:" + node.LocalName);
  36. Console.WriteLine("InnerText=" + node.InnerText);
  37. Console.WriteLine("value="+node.Value);
  38. Console.WriteLine("NamespaceURI=" + node.NamespaceURI);
  39. Console.WriteLine("Prefix=" + node.Prefix);
  40. Console.WriteLine("BaseURI=" + node.BaseURI);
  41. Console.WriteLine("IsReadOnly=" + node.IsReadOnly);
  42.  
  43. //获取属性
  44. XmlAttributeCollection attributes = node.Attributes;
  45. if (attributes != null)
  46. {
  47. XmlAttribute nameAtt = attributes["name"];
  48. if (nameAtt != null)
  49. Console.WriteLine("name="+nameAtt.Value);
  50. }
  51. //是否有子节点
  52. if (node.HasChildNodes)
  53. {
  54. }
  55. }
  56. }
  57. }
  58. }


运行测试

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号