<?xml version="1.0" encoding="UTF-8"?><Message MsgID="1027" >
<DataRow id=1>
<purDeptId>111</purDeptId>
<localClassification>AAA</localClassification>
<suppId>120010</suppId>
</DataRow>
<DataRow id=2>
<purDeptId>2221</purDeptId>
<localClassification>bbb</localClassification>
<suppId>120011</suppId>
</DataRow>
</Message>
请问用C#怎么创建类似上面的XML??
如果需要全部Xml内容的话,用个StringWriter在XmlDocument.Save方法 XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><ha>sdf</ha></root>"); StringWriter sw = new StringWriter();
xdoc.Save(sw);
sw.Close();
Console.WriteLine(sw);
http://blog.csdn.net/amandag/archive/2008/07/08/2623322.aspx
XmlDocument xml=new XmlDocument();
xml.loadXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
"<DataRow id=1>"+
"<purDeptId>111</purDeptId>"+
"<localClassification>AAA</localClassification>"+
"<suppId>120010</suppId>"+
"</DataRow>"
{
XmlDocument xdoc = new XmlDocument();
XmlDeclaration dec = xdoc.CreateXmlDeclaration("1.0", "UTF-8", null);
xdoc.AppendChild(dec);
XmlElement root = xdoc.CreateElement("Message");
xdoc.CreateAttribute("MsgID").Value = "\"1027\"";
int count =1;
XmlElement nod=null;
foreach(DataRow dr in dts.Rows)
{
nod= xdoc.CreateElement("DataRow");
nod.InnerText = (count).ToString(); XmlElement node1 = xdoc.CreateElement("purDeptId");
node1.InnerText = dr["purDeptId"].ToString(); XmlElement node2 = xdoc.CreateElement("localClassification");
node2.InnerText = dr["localClassification"].ToString(); XmlElement node3 = xdoc.CreateElement("suppId");
node3.InnerText = dr["suppId"].ToString(); nod.AppendChild(node1);
nod.AppendChild(node2);
nod.AppendChild(node3);
count++;
root.AppendChild(nod);
}
xdoc.AppendChild(root);
xdoc.Save(filepath);
}调用。
DataTable dt = new DataTable();
dt.Columns.Add("purDeptId", typeof(int));
dt.Columns.Add("localClassification", typeof(string));
dt.Columns.Add("suppId", typeof(int));
DataRow dr=dt.NewRow();
dr["purDeptId"]=111;
dr["localClassification"] = "AAA";
dr["suppId"] = 120010;
dt.Rows.Add(dr); DataRow dr1 = dt.NewRow();
dr1["purDeptId"] = 2221;
dr1["localClassification"] = "bbb";
dr1["suppId"] = 120010;
dt.Rows.Add(dr1);
Xdocument(dt,@"c:\mesg.xml");