如何使用c#中的XMLDocument删除XML文件的第一行?

时间:2021-08-14 19:26:18

I am reading an XML file in C# using XMLDocument. My code goes like this:

我正在使用XMLDocument读取c#中的XML文件。我的代码是这样的:

XmlDocument doc = new XmlDocument();
doc.Load(xmlSourceFile);

First line of my XML document is

我的XML文档的第一行是

<?xml version="1.0" encoding="UTF-8"?>

I have to delete this line. How should I?

我必须删除这一行。我该如何?

5 个解决方案

#1


19  

I don't see why you would want to remove that. But if it is required, you could try this:

我不明白你为什么要删除它。但如果需要的话,你可以试试:

XmlDocument doc = new XmlDocument();
doc.Load("something");

foreach (XmlNode node in doc)
{
    if (node.NodeType == XmlNodeType.XmlDeclaration)
    {
        doc.RemoveChild(node);
    }
}

or with LINQ:

或用LINQ:

var declarations = doc.ChildNodes.OfType<XmlNode>()
    .Where(x => x.NodeType == XmlNodeType.XmlDeclaration)
    .ToList();

declarations.ForEach(x => doc.RemoveChild(x));

#2


6  

I needed to have an XML serialized string without the declaration header so the following code worked for me.

我需要一个不带声明头的XML序列化字符串,这样下面的代码就可以工作了。

StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings {
    Indent = true,
    OmitXmlDeclaration = true, // this makes the trick :)
    IndentChars = "  ",
    NewLineChars = "\n",
    NewLineHandling = NewLineHandling.Replace
};
using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
    doc.Save(writer);
}
return sb.ToString();

#3


5  

Alternatively you can use this;

或者你也可以用这个;

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
if (xmlDoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
    xmlDoc.RemoveChild(xmlDoc.FirstChild);

#4


1  

I understand the need to eliminate the XML Declaration; I'm working on a script that alters the content of an application's preferences.xml, and the application doesn't read the file properly if the declaration is there (not sure why the developers decided to omit the XML declaration).

我理解消除XML声明的必要性;我正在编写一个修改应用程序首选项内容的脚本。如果声明存在,应用程序就不能正确读取文件(不确定为什么开发人员决定省略xml声明)。

Instead of messing around with the XML any longer, I just created a removeXMLdeclaration() method that reads the XML file and removes the first line, then rewrites it back simply using streamreaders/writers. It's lightning fast, and works great! I just call the method after I've done all my XML alteration to clean the file up once and for all.

我只是创建了一个remo俊mldeclaration()方法,该方法读取XML文件并删除第一行,然后使用streamreader /writer重新写入。它闪电般的速度,效果很好!在完成了所有XML修改之后,我就调用这个方法来彻底清理文件。

Here is the code:

这是代码:

public void removeXMLdeclaration()
    {
        try
        {
            //Grab file
            StreamReader sr = new StreamReader(xmlPath);

            //Read first line and do nothing (i.e. eliminate XML declaration)
            sr.ReadLine();
            string body = null;
            string line = sr.ReadLine();
            while(line != null) // read file into body string
            {
                body += line + "\n";
                line = sr.ReadLine();
            }
            sr.Close(); //close file

            //Write all of the "body" to the same text file
            System.IO.File.WriteAllText(xmlPath, body);
        }
        catch (Exception e3)
        {
            MessageBox.Show(e3.Message);
        }

    }

#5


-1  

There is another way to close this file use file stream.

还有一种方法可以关闭这个文件使用文件流。

public void xyz ()
{
       FileStream file = new FileStream(xmlfilepath, FileMode.Open, FileAccess.Read);
       XmlDocument doc = new XmlDocument();
       doc.load(xmlfilepath);

      // do whatever you want to do with xml file

      //then close it by 
      file.close();
      File.Delete(xmlfilepath);
}

#1


19  

I don't see why you would want to remove that. But if it is required, you could try this:

我不明白你为什么要删除它。但如果需要的话,你可以试试:

XmlDocument doc = new XmlDocument();
doc.Load("something");

foreach (XmlNode node in doc)
{
    if (node.NodeType == XmlNodeType.XmlDeclaration)
    {
        doc.RemoveChild(node);
    }
}

or with LINQ:

或用LINQ:

var declarations = doc.ChildNodes.OfType<XmlNode>()
    .Where(x => x.NodeType == XmlNodeType.XmlDeclaration)
    .ToList();

declarations.ForEach(x => doc.RemoveChild(x));

#2


6  

I needed to have an XML serialized string without the declaration header so the following code worked for me.

我需要一个不带声明头的XML序列化字符串,这样下面的代码就可以工作了。

StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings {
    Indent = true,
    OmitXmlDeclaration = true, // this makes the trick :)
    IndentChars = "  ",
    NewLineChars = "\n",
    NewLineHandling = NewLineHandling.Replace
};
using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
    doc.Save(writer);
}
return sb.ToString();

#3


5  

Alternatively you can use this;

或者你也可以用这个;

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
if (xmlDoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
    xmlDoc.RemoveChild(xmlDoc.FirstChild);

#4


1  

I understand the need to eliminate the XML Declaration; I'm working on a script that alters the content of an application's preferences.xml, and the application doesn't read the file properly if the declaration is there (not sure why the developers decided to omit the XML declaration).

我理解消除XML声明的必要性;我正在编写一个修改应用程序首选项内容的脚本。如果声明存在,应用程序就不能正确读取文件(不确定为什么开发人员决定省略xml声明)。

Instead of messing around with the XML any longer, I just created a removeXMLdeclaration() method that reads the XML file and removes the first line, then rewrites it back simply using streamreaders/writers. It's lightning fast, and works great! I just call the method after I've done all my XML alteration to clean the file up once and for all.

我只是创建了一个remo俊mldeclaration()方法,该方法读取XML文件并删除第一行,然后使用streamreader /writer重新写入。它闪电般的速度,效果很好!在完成了所有XML修改之后,我就调用这个方法来彻底清理文件。

Here is the code:

这是代码:

public void removeXMLdeclaration()
    {
        try
        {
            //Grab file
            StreamReader sr = new StreamReader(xmlPath);

            //Read first line and do nothing (i.e. eliminate XML declaration)
            sr.ReadLine();
            string body = null;
            string line = sr.ReadLine();
            while(line != null) // read file into body string
            {
                body += line + "\n";
                line = sr.ReadLine();
            }
            sr.Close(); //close file

            //Write all of the "body" to the same text file
            System.IO.File.WriteAllText(xmlPath, body);
        }
        catch (Exception e3)
        {
            MessageBox.Show(e3.Message);
        }

    }

#5


-1  

There is another way to close this file use file stream.

还有一种方法可以关闭这个文件使用文件流。

public void xyz ()
{
       FileStream file = new FileStream(xmlfilepath, FileMode.Open, FileAccess.Read);
       XmlDocument doc = new XmlDocument();
       doc.load(xmlfilepath);

      // do whatever you want to do with xml file

      //then close it by 
      file.close();
      File.Delete(xmlfilepath);
}