我需要在这里创建如何生成一个XML文件
bool result= false;
一个XML文件如何在ASP.NET中使用C#语法实现这一目标。 result
是我需要在XML文件中添加的值。
我需要创建一个文件夹下的XML文件,像这样
<?xml version="1.0" encoding="utf-8" ?>
<user>
<Authenticated>yes</Authenticated>
</user>
内容谢谢
我需要在这里创建如何生成一个XML文件
bool result= false;
一个XML文件如何在ASP.NET中使用C#语法实现这一目标。 result
是我需要在XML文件中添加的值。
我需要创建一个文件夹下的XML文件,像这样
<?xml version="1.0" encoding="utf-8" ?>
<user>
<Authenticated>yes</Authenticated>
</user>
内容谢谢
如何:
XmlTextWriter xtw = new XmlTextWriter(@"yourfilename.xml", Encoding.UTF8);
xtw.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");
xtw.WriteStartElement("user");
xtw.WriteStartElement("Authenticated");
xtw.WriteValue(result);
xtw.WriteEndElement(); // Authenticated
xtw.WriteEndElement(); // user
xtw.Flush();
xtw.Close();
或者如果你喜欢建立在内存中的XML文件,你也可以使用XmlDocument
类及其方法:
// Create XmlDocument and add processing instruction
XmlDocument xdoc = new XmlDocument();
xdoc.AppendChild(xdoc.CreateProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\""));
// generate <user> element
XmlElement userElement = xdoc.CreateElement("user");
// create <Authenticated> subelement and set it's InnerText to the result value
XmlElement authElement = xdoc.CreateElement("Authenticated");
authElement.InnerText = result.ToString();
// add the <Authenticated> node as a child to the <user> node
userElement.AppendChild(authElement);
// add the <user> node to the XmlDocument
xdoc.AppendChild(userElement);
// save to file
xdoc.Save(@"C:\yourtargetfile.xml");
应在.NET Framework的任何版本,如果你有你的文件的顶部using System.Xml;
条款。
马克
XElement xml = new XElement("user",
new XElement("Authenticated","Yes"))
);
xml.Save(savePath);
它适用于.NET 3以上,但 您可以使用XmlDocument的对更高版本
XmlDocument xmlDoc = new XmlDocument();
// Write down the XML declaration
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0","utf-8",null);
// Create the root element
XmlElement rootNode = xmlDoc.CreateElement("user");
xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
xmlDoc.AppendChild(rootNode);
// Create the required nodes
XmlElement mainNode = xmlDoc.CreateElement("Authenticated");
XmlText yesText= xmlDoc.CreateTextNode("Yes");
mainNode.AppendChild(yesText);
rootNode.AppendChild(mainNode);
xmlDoc.Save(savePath);
您也可以使用XmlWriter作为建议@marc_s或至少你可以存储XML的文件中像刺
using(StreamWriter sw = new StreamWriter(savePath))
{
sw.Write(string.Format("<?xml version=\"1.0\" encoding=\"utf-8\" ?>
<user><Authenticated>{0}</Authenticated></user>","Yes"));
}
我没有找到name属性一样的XElement – happysmile 2009-10-09 09:50:03
它的作品.NET 3.5及以上 – 2009-10-09 10:19:10
如果你想生成XML,然后给用户一个选择保存XML在他们的工作站,检查下面的文章。它详细解释了这个过程。
提供示例代码可以保证您的文章对未来用户有用。 ;) – vdbuilder 2012-11-07 18:08:51
谢谢marc_s。 它工作的很好 – happysmile 2009-10-09 10:44:10