C# study notes XML

Use TextWriter to generate XML file, the program uses SAX method:

	#region 使用SAX方式处理XML
	static void XmlTextWriteTest() {
    
    
		const string filename = "sampledate.xml";
	
		XmlTextWriter writer;
		writer = new XmlTextWriter(filename, null);
		// 为使文件易读,使用缩进
		writer.Formatting = Formatting.Indented;
		// 写XML声明
		writer.WriteStartDocument();
	
		// 引用样式
		string PItext = "type='text/xsl'href='book.xsl'";
		writer.WriteProcessingInstruction("xml-stylesheet", PItext);
		// 文档类型
		writer.WriteDocType("book", null, null, "<!ENTITY h 'hardcover'>");
		// 写入注释
		writer.WriteComment("sample XML");
	
		// 写一个元素(根元素)
		writer.WriteStartElement("book");
		// 属性
		writer.WriteAttributeString("genre", "novel");
		writer.WriteAttributeString("ISBN", "1 - 8630 - 014");
	
		// 书名元素
		writer.WriteElementString("title", "The Handmaid's Tale");
		// Write the style element
		writer.WriteStartElement("style");
		writer.WriteEntityRef("h");
		writer.WriteEndElement();
	
		// 价格元素
		writer.WriteElementString("price", "19.95");
		// 写入CDATA
		writer.WriteCData("Prices 15% off!!");
		// 关闭根元素
		writer.WriteEndElement();
		writer.WriteEndDocument();
	
		writer.Flush();
		writer.Close();
	
		// 加载文件
		XmlDocument doc = new XmlDocument();
		doc.PreserveWhitespace = true;
		doc.Load(filename);
		// XML文件的内容显示在控制台
		Console.WriteLine(doc.InnerXml);
	}
	#endregion

operation result:
Insert picture description here

Use DOM mode to process XML.

	#region 使用DOM模式来处理XML
	static void XmlDocumentTest() {
    
    
		XmlDocument xd = new XmlDocument();
		try {
    
    
			xd.Load(@".\BookList.xml");
		} catch (XmlException e) {
    
    
			Console.WriteLine("Exception caught:" + e.ToString());
		}

		XmlNode doc = xd.DocumentElement;

		if (doc.HasChildNodes) ProcessChildren(doc, 0);
	}

	private static void ProcessChildren(XmlNode xn, int level) {
    
    
		string istr;
		istr = Indent(level);
		switch (xn.NodeType) {
    
    
			case XmlNodeType.Comment:
				Console.WriteLine(istr + "<!--" + xn.Value + "-->");
				break;
			case XmlNodeType.ProcessingInstruction:
				Console.WriteLine(istr + "<?" + xn.Name + " " + xn.Value + " ?>");
				break;
			case XmlNodeType.Text:
				Console.WriteLine(istr + xn.Value);
				break;
			case XmlNodeType.Element:
				XmlNodeList ch = xn.ChildNodes;
				Console.Write(istr + "<" + xn.Name);

				XmlAttributeCollection atts = xn.Attributes;    // 处理属性
				if (atts != null) {
    
    
					foreach (XmlNode at in atts)
						Console.Write(" " + at.Name + "=" + at.Value);
				}
				Console.WriteLine(">");

				foreach (XmlNode nd in ch)
					ProcessChildren(nd, level + 2);             // 对子节点递归调用
				Console.WriteLine(istr + "</" + xn.Name + ">");
				break;
			default:
				break;
		}
	}

	private static string Indent(int level) {
    
    
		if (level == 0) return "";
		return new String(' ', level);
	}
	#endregion

operation result:
Insert picture description here

Use XSLT to transform XML.

	#region 使用XSLT转换XML
	static void XslTransformTest() {
    
    
		try {
    
    
			XmlDocument doc = new XmlDocument();
			doc.Load(@".\BookList.xml");

			XPathNavigator nav = doc.CreateNavigator();
			nav.MoveToRoot();

			XslTransform xt = new XslTransform();
			xt.Load(@".\BookList.xslt");

			XmlTextWriter writer = new XmlTextWriter(Console.Out);

			xt.Transform(nav, null, writer);
		} catch (XmlException e) {
    
    

			Console.WriteLine("XML Exception:" + e.ToString());
		} catch (XsltException e) {
    
    

			Console.WriteLine("XSLT Exception:" + e.ToString());
		}


	}

	#endregion

Link to XML

System.Xml.LinqLing to XMLThe support provided by the namespace .

1. Construct and write XML

XDocument, XElement and XText, XAttribute in this namespace provide key methods for reading and writing XML documents. Use the XDocument constructor to construct an XML document object; use the XElement object to construct an XML node element, use the XAttribute constructor to construct the element's attributes; use the XText constructor to construct the text in the node.
Using Linq to XML can be constructed much like the way XML itself is written.

	public static void WriteXml() {
    
    

		// 构造XML
		var xDoc = new XDocument(new XElement("root",
			new XElement("dog",
				new XText("小狗"),
				new XAttribute("color", "black")),
			new XElement("cat"),
			new XElement("pig", "小猪")));

		// 写入文件
		StreamWriter sw = new StreamWriter(
			new FileStream(@"E:\Visual Studio 2019\C#\Mooc学习\ConsoleApp020XML\bin\Debug\t.xml", FileMode.Create),
			Encoding.UTF8);
		xDoc.Save(sw);

		// 显示控制台
		xDoc.Save(Console.Out);

		sw.Close();
	}

The file content of the program running result is:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <dog color="black">小狗</dog>
  <cat />
  <pig>小猪</pig>
</root>

Note that it is uf-8 encoding. The encoding on the console is the default g2312:

<?xml version="1.0" encoding="gb2312"?>
<root>
  <dog color="black">小狗</dog>
  <cat />
  <pig>小猪</pig>
</root>

2. Read and query XML

LinqThe main purpose is to query objects from the collection, the Linq to XMLcollection is by XElementthe Elements(), Elements(string name), Descendants, DescendantsAndSelf, Ancestors, AncestorAndSelfobtained in several methods.
After obtaining the XElementcollection, you can obtain the attribute value of the element by XElementthe Attribute(string name)method, and the text value of the node can be obtained by XElementthe Valueattribute; Linqit can be easily used for query, filtering and sorting.

	#region 读取和查询XML
	public static void ReadXml() {
    
    

		// 读入文件
		var xDoc = XDocument.Load(@"E:\Visual Studio 2019\C#\Mooc学习\ConsoleApp020XML\bin\Debug\t.xml");

		// 进行处理
		var query = from item in xDoc.Element("root").Elements()
					select new {
    
    
						TypeName = item.Name,
						Saying = item.Value,
						Color = item.Attribute("color") == null ? null : item.Attribute("color").Value
					};
		foreach (var item in query) {
    
    
			Console.WriteLine("{0}'s color is {1}, {0} said {2}",
				item.TypeName,
				item.Color ?? "Unknown",
				item.Saying ?? "nothing");
		}
	}
	#endregion

The display results of the program running are as follows:

dog's color is black, dog said 小狗
cat's color is Unknown, cat said
pig's color is Unknown, pig said 小猪

Guess you like

Origin blog.csdn.net/qq_45349225/article/details/114795867