28

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

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

我的 XML 文档的第一行是

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

我必须删除这一行。我该怎么办?

4

6 回答 6

34

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

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

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

或使用 LINQ:

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

declarations.ForEach(x => doc.RemoveChild(x));
于 2013-04-16T12:24:58.160 回答
11

我需要一个没有声明头的 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();
于 2016-05-03T07:17:57.270 回答
8

或者,您可以使用它;

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
if (xmlDoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
    xmlDoc.RemoveChild(xmlDoc.FirstChild);
于 2016-01-13T11:29:31.703 回答
3

一个非常快速和简单的解决方案是使用类的DocumentElement属性XmlDocument

XmlDocument doc = new XmlDocument();
doc.Load(xmlSourceFile);
Console.Out.Write(doc.DocumentElement.OuterXml);
于 2018-07-24T07:51:03.780 回答
1

我理解消除 XML 声明的必要性;我正在编写一个更改应用程序内容的脚本,preferences.xml如果声明存在,则应用程序无法正确读取文件(不知道为什么开发人员决定省略 XML 声明)。

我不再搞乱 XML,而是创建了一个removeXMLdeclaration()方法来读取 XML 文件并删除第一行,然后简单地使用流读取器/写入器将其重写回来。它的速度快如闪电,而且效果很好!我只是在完成所有 XML 更改以一劳永逸地清理文件后调用该方法。

这是代码:

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);
        }

    }
于 2014-04-09T17:52:56.710 回答
0

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

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);
}
于 2014-10-17T18:07:21.050 回答