C# 生成 XML 的问题,求高手帮小弟看下
请高手帮忙看下,我搞了两天没搞出来,郁闷:
xmlDoc.Load(System.Web.HttpContext.Current.Server.MapPath( "UserXML/RightXml.xml "));
XmlNode root1 = xmlDoc.SelectSingleNode( "UserInfo "); //查找 <bookstore>
//XmlElement xe1 = xmlDoc.CreateElement( "From "); //创建一个 <From> 节点
//xe1.SetAttribute( "xename ", strFormNo); //设置该节点xename属性
//xe1.SetAttribute( "Quest ", dtFlows.Rows.Count.ToString());
//XmlNode root2 = xmlDoc.SelectSingleNode( "From ");
for (int i = 0; i < dtFlows.Rows.Count; i++)
{
XmlElement xe2 = xmlDoc.CreateElement( "From " + strFormNo);
xe2.SetAttribute( "TypeInfo ", strFormNo + "_ " + i.ToString()); //设置该节点genre属性
xe2.SetAttribute( "DateTime ", DateTime.Now.ToString());
XmlElement xesub2 = xmlDoc.CreateElement( "FlowCode ");
xesub2.InnerText = dtFlows.Rows[i][ "fFlowCode "].ToString().Trim(); //设置文本节点
xe2.AppendChild(xesub2);
XmlElement xesub3 = xmlDoc.CreateElement( "FlowName ");
xesub3.InnerText = dtFlows.Rows[i][ "fFlowName "].ToString().Trim(); //设置文本节点
xe2.AppendChild(xesub3);
XmlElement xesub4 = xmlDoc.CreateElement( "Enable ");
xesub4.InnerText = dtFlows.Rows[i][ "fEnable "].ToString().Trim(); //设置文本节点
xe2.AppendChild(xesub4);
XmlElement xesub5 = xmlDoc.CreateElement( "Ignore ");
xesub5.InnerText = dtFlows.Rows[i][ "fIgnore "].ToString().Trim(); //设置文本节点
xe2.AppendChild(xesub5);
root1.AppendChild(xe2);
}
得到如下格式的 XML 代码:
<?xml version= "1.0 " encoding= "utf-8 "?>
<UserInfo>
<FromISO001 TypeInfo= "ISO001_0 " DateTime= "2007-4-25 16:45:22 ">
<FlowCode> A </FlowCode>
<FlowName> 数据输入 </FlowName>
<Enable> False </Enable>
<Ignore> False </Ignore>
</FromISO001>
<FromISO001 TypeInfo= "ISO001_1 " DateTime= "2007-4-25 16:45:22 ">
<FlowCode> B </FlowCode>
<FlowName> 数据复核 </FlowName>
<Enable> False </Enable>
<Ignore> False </Ignore>
</FromISO001>
<FromISO001 TypeInfo= "ISO001_2 " DateTime= "2007-4-25 16:45:22 ">
<FlowCode> C </FlowCode>
<FlowName> 数据审核 </FlowName>
<Enable> False </Enable>
<Ignore> False </Ignore>
</FromISO001>
</UserInfo>
要怎么改才能得到这样的格式 XML 呢,就是加多一级,我之前没用过 XML ,所以不懂?
<?xml version= "1.0 " encoding= "utf-8 "?>
<UserInfo>
<From>
<FromISO001 TypeInfo= "ISO001_0 " DateTime= "2007-4-25 16:45:22 ">
<FlowCode> A </FlowCode>
<FlowName> 数据输入 </FlowName>
<Enable> False </Enable>
<Ignore> False </Ignore>
</FromISO001>
<FromISO001 TypeInfo= "ISO001_1 " DateTime= "2007-4-25 16:45:22 ">
<FlowCode> B </FlowCode>
<FlowName> 数据复核 </FlowName>
<Enable> False </Enable>
<Ignore> False </Ignore>
</FromISO001>
<FromISO001 TypeInfo= "ISO001_2 " DateTime= "2007-4-25 16:45:22 ">
<FlowCode> C </FlowCode>
<FlowName> 数据审核 </FlowName>
<Enable> False </Enable>
<Ignore> False </Ignore>
</FromISO001>
</From>
</UserInfo>
[解决办法]
先创建 <From> (XmlElement xe1 = xmlDoc.CreateElement( "From ");) 再循环创建xe2 添加到时候从里往外添 xe1.AppendChild(xe2); root1.AppendChild(xe1); 就好了