C#有两种创建XML文档的方法
1.XmlDocument
2.Linq to XML
第一种:XmlDocument
结果:[xml文件如下]
<?xml version="1.0" encoding="UTF-8"?>
<ns0:Z_AVS_UPLOAD_WEIGHT_Request xmlns:ns0="http://schemas.microsoft.com/BizTalk/2003">
<ZWERKS>ZFM1</ZWERKS>
<TAB1>
<ZNO>13022101</ZNO>
<ZORDER>2013238955</ZORDER>
<ZWEIGHT>4140</ZWEIGHT>
</TAB1>
<TAB1>
<ZNO>13022101</ZNO>
<ZORDER>2013239627</ZORDER>
<ZWEIGHT>4140</ZWEIGHT>
</TAB1>
</ns0:Z_AVS_UPLOAD_WEIGHT_Request>
实现:[XmlDocument]
XmlDocument document = new XmlDocument();//创建XmlDocument对象
XmlDeclaration declaration = document.CreateXmlDeclaration("1.0", "UTF-8", "");//xml文档的声明部分
document.AppendChild(declaration);
XmlElement root = document.CreateElement("ns0", "Z_AVS_UPLOAD_WEIGHT_Request", "http://schemas.microsoft.com/BizTalk/2003");
document.AppendChild(root);
XmlElement zwerks = document.CreateElement("ZWERKS");
zwerks.InnerText = "ZFM1";
root.AppendChild(zwerks);
XmlElement tab1 = document.CreateElement("TAB1");
root.AppendChild(tab1);
XmlElement zno = document.CreateElement("ZNO");
zno.InnerText = "13022101";
tab1.AppendChild(zno);
XmlElement zorder = document.CreateElement("ZORDER");
zorder.InnerText = "2013238955";
tab1.AppendChild(zorder);
XmlElement zweight = document.CreateElement("ZWEIGHT");
zweight.InnerText = "4140";
tab1.AppendChild(zweight);
XmlElement tab2 = document.CreateElement("TAB1");
root.AppendChild(tab2);
XmlElement zno2 = document.CreateElement("ZNO");
zno2.InnerText = "13022101";
tab2.AppendChild(zno2);
XmlElement zorder2 = document.CreateElement("ZORDER");
zorder2.InnerText = "2013238955";
tab2.AppendChild(zorder2);
XmlElement zweight2 = document.CreateElement("ZWEIGHT");
zweight2.InnerText = "4140";
tab2.AppendChild(zweight2);
document.Save("test.xml");//将生成好的xml保存到test.xml文件中
第二种:Linq to XML
结果:[xml文件如下]
<a>
<xingming>
<item>
<name>张三</name>
<code>1</code>
</item>
<item>
<name>李四</name>
<code>2</code>
</item>
<item>
<name>王五</name>
<code>3</code>
</item>
<item>
<name>赵四</name>
<code>4</code>
</item>
<item>
<name>王二麻子</name>
<code>5</code>
</item>
</xingming>
<nianji>
<item>
<name>一年级</name>
<banji>一班</banji>
</item>
</nianji>
</a>
实现:[Linq to XML]
XDocument document = new XDocument();
document.Declaration = new XDeclaration("1.0", "UTF-8", "");
XNamespace ns = "http://schemas.microsoft.com/BizTalk/2003";
XElement root = new XElement(ns + "Z_AVS_UPLOAD_WEIGHT_Request",
new XAttribute(XNamespace.Xmlns + "ns0", "http://schemas.microsoft.com/BizTalk/2003"));
root.Add(new XElement("ZWERKS", "ZFM1"),
new XElement("TAB1",
new XElement("ZNO", 13022101),
new XElement("ZORDER", 2013238955),
new XElement("ZWEIGHT", 4140)),
new XElement("TAB1",
new XElement("ZNO", 13022101),
new XElement("ZORDER", 2013238955),
new XElement("ZWEIGHT", 4140))
);
document.Add(root);
document.Save("test.xml");//保存xml到文件