[英]Append xml document to bottom of existing xml doc
我有一個xml文檔,並希望在其底部附加另一個xml。 使用.NET中的xml類,最快的方法是什么(在3.5中)?
謝謝
以最有效率最快,最快最簡單? 例如:
XDocument doc1 = XDocument.Load(...);
XDocument doc2 = XDocument.Load(...);
// Copy the root element of doc2 to the end of doc1
doc1.Root.Add(doc2.Root);
doc1.Save(...);
或者,您可能需要:
// Copy the *contents* of the root element of doc2 to the end of doc1
doc1.Root.Add(doc2.Root.Descendants());
如果您可以更准確地了解您的要求,我們可能會提供更多幫助。 請注意,XML文檔只能有一個根元素,因此您不能只放置一個文檔。
我懷疑你能用XML類做到這一點。 XML庫通常旨在保護您免於創建格式不良的XML,並且兩個XML文檔的串聯將很難形成,因為文檔節點將具有兩個子元素。
如果.Net庫允許你這樣做,我建議你把它作為一個bug提出來。
var xml = new XmlDocument();
xml.AppendChild(...);
xml.PrependChild(...);
如果您真的想要添加第二個根節點,最快的方法是逐行讀取第一個文件並將其添加到第二個文件中。 這是一種非常臟的方式,你會得到一個無效的 xml文件!
System.IO.StreamWriter file1 = System.IO.File.AppendText(path);
System.IO.StreamReader file2 = new System.IO.StreamReader(path2)
while(!file2.EndOfStream)
{
file1.WriteLine(file2.ReadLine());
}
file1.Close();
file2.Close();
我甚至不喜歡這個解決方案!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.