且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用C#创建XML格式

更新时间:2022-04-02 04:49:51

只需使用 Google ,你可以在网上找到很多教程。

例如,尝试阅读本文: C#XmlWriter [ ^ ]。
Just using Google, you may find many tutorials on the web.
For instance, try reading this one: C# XmlWriter[^].


一个非常基本的表格让你前进,你可以根据需要改进代码。





A very basic form that get you going and you can improve the code as you want.


static void CreateXML()
{
    XmlDocument doc = new XmlDocument();

    XmlNode rootNode = doc.CreateElement("etaalup_count");
    doc.AppendChild(rootNode);

    XmlNode countNode = doc.CreateElement("countnodes");
    XmlAttribute serviceAttribute = doc.CreateAttribute("serviceid");
    serviceAttribute.Value = "A022114704152";
    countNode.Attributes.Append(serviceAttribute);
    XmlAttribute countAttribute = doc.CreateAttribute("count");
    countAttribute.Value = "10";
    countNode.Attributes.Append(countAttribute);
    rootNode.AppendChild(countNode);

    countNode = doc.CreateElement("countnodes");
    serviceAttribute = doc.CreateAttribute("serviceid");
    serviceAttribute.Value = "A022114704153";
    countNode.Attributes.Append(serviceAttribute);
    countAttribute = doc.CreateAttribute("count");
    countAttribute.Value = "15";
    countNode.Attributes.Append(countAttribute);
    rootNode.AppendChild(countNode);

    countNode = doc.CreateElement("countnodes");
    serviceAttribute = doc.CreateAttribute("serviceid");
    serviceAttribute.Value = "A022114704154";
    countNode.Attributes.Append(serviceAttribute);
    countAttribute = doc.CreateAttribute("count");
    countAttribute.Value = "5";
    countNode.Attributes.Append(countAttribute);

    rootNode.AppendChild(countNode);
    doc.Save(Console.Out);
}


XmlWriter类的WriteChars方法将字符写入XML。它需要一个字符数组并一次写入一个字符。



以下代码片段采用一系列字符并将它们写入XML文件。



使用(XmlWriter writer = XmlWriter.Create(M.xml)){

writer.WriteStartDocument();



char [] ch = new char [6];

ch [0] ='m';

ch [1] ='a';

ch [2] ='h';

ch [3] ='e';

ch [4] ='s';

ch [5] ='h';



writer.WriteStartElement(WriteChars);



writer.WriteChars(ch,0,ch .Length);



writer.WriteEndElement();



writer.WriteEndDocument();



}
The WriteChars method of the XmlWriter class writes characters to XML. It takes an array of characters and writes one character at a time.

The following code snippet takes an array of characters and writes them to an XML file.

using (XmlWriter writer = XmlWriter.Create("M.xml")) {
writer.WriteStartDocument();

char[] ch = new char[6];
ch[0] = 'm';
ch[1] = 'a';
ch[2] = 'h';
ch[3] = 'e';
ch[4] = 's';
ch[5] = 'h';

writer.WriteStartElement("WriteChars");

writer.WriteChars(ch, 0, ch.Length);

writer.WriteEndElement();

writer.WriteEndDocument();

}