using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace _21_XML
{
class Program
{
static void Main(string[] args)
{
//创建xml
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(dec);
//根节点order
XmlElement order =doc.CreateElement("order");
doc.AppendChild(order);
XmlElement customerName = doc.CreateElement("customerName");
customerName.InnerText = "喂喂";
order.AppendChild(customerName);
XmlElement orderNo = doc.CreateElement("OrderNo");
orderNo.InnerText = "tj000001";
order.AppendChild(orderNo);
XmlElement items = doc.CreateElement("Items");
order.AppendChild(items);
XmlElement orderItem1 = doc.CreateElement("OrderItem");
orderItem1.SetAttribute("Name", "媳妇");
orderItem1.SetAttribute("Count", "10");
items.AppendChild(orderItem1);
XmlElement orderItem2 = doc.CreateElement("OrderItem");
orderItem2.SetAttribute("Name", "房子");//指定名称的属性
orderItem2.SetAttribute("Count", "10");
items.AppendChild(orderItem2);
//保存到文件
doc.Save("order.xml");
Console.Read();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace _21_XML
{
class Program
{
static void Main(string[] args)
{
//创建xml
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(dec);
//根节点order
XmlElement order =doc.CreateElement("order");
doc.AppendChild(order);
XmlElement customerName = doc.CreateElement("customerName");
customerName.InnerText = "喂喂";
order.AppendChild(customerName);
XmlElement orderNo = doc.CreateElement("OrderNo");
orderNo.InnerText = "tj000001";
order.AppendChild(orderNo);
XmlElement items = doc.CreateElement("Items");
order.AppendChild(items);
XmlElement orderItem1 = doc.CreateElement("OrderItem");
orderItem1.SetAttribute("Name", "媳妇");
orderItem1.SetAttribute("Count", "10");
items.AppendChild(orderItem1);
XmlElement orderItem2 = doc.CreateElement("OrderItem");
orderItem2.SetAttribute("Name", "房子");//指定名称的属性
orderItem2.SetAttribute("Count", "10");
items.AppendChild(orderItem2);
//保存到文件
doc.Save("order.xml");
Console.Read();
}
}
}
本文演示了如何使用C#创建并保存XML文档,包括创建XML声明、定义根节点、添加子节点以及保存到文件的过程。

被折叠的 条评论
为什么被折叠?



