将字符串文本写入Xml文件

时间:2015-10-09 13:25:57

标签: c# xml file

我想在父节点之前的Xml文件的开头写字符串文本。请告诉我如何写字符串文本。在Xml节点之上。

{
    XmlTextWriter writer = new XmlTextWriter("product.xml", System.Text.Encoding.UTF8);
    //string x="<!-- sitemap-generator-url="http://www.auditmypc.com/free-sitemap-generator.asp --> ";
    string y= "<!-- This sitemap was created using the free tool found here: http://www.auditmypc.com/free-sitemap-generator.asp -->";
    string z= "<!-- Audit My PC also offers free security tools to help keep you safe during internet travels -->";

    writer.WriteStartDocument(true);
    writer.Formatting = Formatting.Indented;
    writer.Indentation = 2;
    writer.WriteStartElement("urlset");
    createNode("1", "url 1", writer);
    createNode("2", "url 2", writer);
    createNode("3", "url 3", writer);
    createNode("4", "url 4", writer);
    writer.WriteEndElement();
    writer.WriteEndDocument();
    writer.Close();
    MessageBox.Show("XML File created ! ");
}

private void createNode(string pID, string pName, XmlTextWriter writer)
{
    writer.WriteStartElement("url");
    writer.WriteStartElement("loc");
    writer.WriteString(pID);
    writer.WriteEndElement();

    writer.WriteEndElement();
}

3 个答案:

答案 0 :(得分:0)

您可以使用XmlTextWriter.WriteComment方法:

XmlTextWriter writer = new XmlTextWriter("product.xml", System.Text.Encoding.UTF8);
writer.WriteStartDocument(true);
writer.WriteComment("This sitemap was created using the free tool found here: http://www.auditmypc.com/free-sitemap-generator.asp");
writer.Formatting = Formatting.Indented;
writer.Indentation = 2;
writer.WriteStartElement("urlset");

输出:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--This sitemap was created using the free tool found here: http://www.auditmypc.com/free-sitemap-generator.asp-->
<urlset />

<?xml ?>标记应该是第一个,因此我们将此评论插入最顶层。

答案 1 :(得分:0)

StackOverflow不会让我对这个问题发表评论,所以我会在这里发帖。

如果XML文件已存在,则将一行添加到顶部的一个选项是将整个文件读入内存或新的临时文件,然后从要添加到顶部的行开始重写该文件。以下是关于在文件前添加一行的其他帖子:

Add a single line to the top of text file

C#: Prepending to beginning of a file

答案 2 :(得分:0)

实际上,您可以在没有XML类的情况下执行此操作:

    string strContent = null, additionalContent = "<!--AdditionalContent-->";
    if (File.Exists(@"yourfile"))
    {
        strContent = File.ReadAllText(@"yourfile");
        File.WriteAllText(@"yourfile", additionalContent + Environment.NewLine + strContent);
    }

请注意,此方法应用于相当小的文件。否则,您需要以较小的块读取文件以适合您的记忆。