我正在使用C#读取XML文件XMLDocument.我的代码是这样的:
XmlDocument doc = new XmlDocument();
doc.Load(xmlSourceFile);
Run Code Online (Sandbox Code Playgroud)
我的XML文档的第一行是
<?xml version="1.0" encoding="UTF-8"?>
Run Code Online (Sandbox Code Playgroud)
我必须删除这一行.我该怎么办?
Mat*_*att 25
我不明白你为什么要删除它.但如果需要,你可以试试这个:
XmlDocument doc = new XmlDocument();
doc.Load("something");
foreach (XmlNode node in doc)
{
if (node.NodeType == XmlNodeType.XmlDeclaration)
{
doc.RemoveChild(node);
}
}
Run Code Online (Sandbox Code Playgroud)
或者使用LINQ:
var declarations = doc.ChildNodes.OfType<XmlNode>()
.Where(x => x.NodeType == XmlNodeType.XmlDeclaration)
.ToList();
declarations.ForEach(x => doc.RemoveChild(x));
Run Code Online (Sandbox Code Playgroud)
小智 7
我需要一个没有声明标头的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();
Run Code Online (Sandbox Code Playgroud)
或者你可以使用这个;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
if (xmlDoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
xmlDoc.RemoveChild(xmlDoc.FirstChild);
Run Code Online (Sandbox Code Playgroud)