private void button1_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xd = xmlDoc.CreateXmlDeclaration("1.0", "GB2312", null);
xmlDoc.AppendChild(xd);
//创建一个root节点
XmlElement xeRoot = xmlDoc.CreateElement("root");
xmlDoc.AppendChild(xeRoot);
XmlElement xeP1 = xmlDoc.CreateElement("Person");
xeP1.SetAttribute("name", "zs");
xeP1.InnerText = "我是张三";
xeP1.SetAttribute("sex", "男");
XmlElement xeP2 = xmlDoc.CreateElement("Person");
xeP2.SetAttribute("name", "ls");
xeP2.InnerText = "我是李四";
xeP2.SetAttribute("sex", "女");
xeRoot.AppendChild(xeP1);
xeRoot.AppendChild(xeP2);
xmlDoc.Save("C:\\cc.xml");
}
//以下是解析代码
StringBuilder sb = new StringBuilder();
private void button2_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("C:\\cc.xml");
if (xmlDoc.HasChildNodes)
{
sb.AppendLine(xmlDoc.DocumentElement.Name);
DGXML(xmlDoc.DocumentElement, 1);
}
textBox1.Text = sb.ToString();
}
private void DGXML(XmlNode xmlParentNode, int cengJi)
{
if (xmlParentNode.HasChildNodes)
{
XmlNodeList xnl = xmlParentNode.ChildNodes;
foreach (XmlNode xn in xnl)
{
if (xn is XmlElement)
{
if (xn.HasChildNodes)
{
sb.AppendLine(xn.Name.PadLeft(xn.Name.Length + cengJi));//填充左边n个空格,已达到右对齐
DGXML(xn, cengJi + 1);
}
}
else if (xn is XmlText)
{
sb.AppendLine(xn.Value.PadLeft(xn.Value.Length + cengJi + 1));
}
}
}
}