将字符串文本写入Xml文件

本文关键字:Xml 文件 字符串 文本 | 更新日期: 2023-09-27 18:16:52

我想在父节点之前的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();
}

将字符串文本写入Xml文件

您可以使用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 ?>标签应该是第一个,所以我们在最上面的地方插入了这个注释

StackOverflow不允许我评论这个问题,所以我将在这里发布。

如果XML文件已经存在,在顶部添加一行的一个选项是将整个文件读入内存或一个新的临时文件,然后从您希望添加到顶部的行开始重写文件。以下是其他一些关于在文件前加行前缀的文章:

在文本文件

顶部添加一行

c#:在文件开头加上前缀

事实上,不需要XML类也可以做到这一点:

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

注意,这种方法应该用于相当小的文件。否则,您需要读取更小的块文件,以适应您的内存。