Use TextWriter para generar un archivo XML, el programa usa el método SAX:
#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
resultado de la operación:
Utilice el modo DOM para procesar 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
resultado de la operación:
Utilice XSLT para transformar 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
Enlace a XML
System.Xml.Linq
Ling to XML
El soporte proporcionado por el espacio de nombres .
1. Construya y escriba XML
XDocument, XElement y XText, XAttribute en este espacio de nombres proporcionan métodos clave para leer y escribir documentos XML. Use el constructor XDocument para construir un objeto de documento XML; use el objeto XElement para construir un elemento de nodo XML, use el constructor XAttribute para construir los atributos del elemento; use el constructor XText para construir el texto en el nodo.
El uso de Linq to XML se puede construir de forma muy similar a la forma en que se escribe XML.
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();
}
El contenido del archivo del resultado de ejecución del programa es:
<?xml version="1.0" encoding="utf-8"?>
<root>
<dog color="black">小狗</dog>
<cat />
<pig>小猪</pig>
</root>
Tenga en cuenta que es codificación uf-8. La codificación en la consola es la g2312 predeterminada:
<?xml version="1.0" encoding="gb2312"?>
<root>
<dog color="black">小狗</dog>
<cat />
<pig>小猪</pig>
</root>
2. Leer y consultar XML
Linq
El propósito principal es el de objetos de consulta de la colección, la Linq to XML
colección es por XElement
el Elements()
, Elements(string name)
, Descendants
, DescendantsAndSelf
, Ancestors
, AncestorAndSelf
obtenido en varios métodos.
Después de obtener la XElement
colección, puede obtener el valor de atributo del elemento a través XElement
del Attribute(string name)
método, y el valor de texto del nodo se puede obtener a través XElement
del Value
atributo; Linq
se puede usar fácilmente para consultas, filtrado y clasificación.
#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
Los resultados de visualización del programa en ejecución son los siguientes:
dog's color is black, dog said 小狗
cat's color is Unknown, cat said
pig's color is Unknown, pig said 小猪