[英]How to modify existing XML file with XmlDocument and XmlNode in C#
[英]How to delete first line of XML file using XMLDocument in C#?
我正在使用XMLDocument
在C#中讀取XML文件。 我的代碼是這樣的:
XmlDocument doc = new XmlDocument();
doc.Load(xmlSourceFile);
我的XML文檔的第一行是
<?xml version="1.0" encoding="UTF-8"?>
我必須刪除這一行。 我該怎么辦?
我不明白你為什么要刪除它。 但如果需要,你可以試試這個:
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));
我需要一個沒有聲明標頭的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();
或者你可以使用這個;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
if (xmlDoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
xmlDoc.RemoveChild(xmlDoc.FirstChild);
我理解消除XML聲明的必要性; 我正在編寫一個改變應用程序的preferences.xml
內容的腳本,如果聲明在那里,應用程序不能正確讀取文件(不確定開發人員為什么決定省略XML聲明)。
我沒有再removeXMLdeclaration()
用XML了,而是創建了一個removeXMLdeclaration()
方法,它讀取XML文件並刪除第一行,然后簡單地使用streamreaders / writers重寫它。 它閃電般快速,效果很好! 在我完成所有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);
}
}
一個非常快速和簡單的解決方案是使用XmlDocument
類的DocumentElement
屬性:
XmlDocument doc = new XmlDocument();
doc.Load(xmlSourceFile);
Console.Out.Write(doc.DocumentElement.OuterXml);
還有另一種方法可以關閉此文件使用文件流。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.