若想要將其中的節點,複製到其他XmlDocument可不能直接放
需使用ImportNode複製到其他的XmlDocument
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace qntest1
{
static class Program
{
///
/// 應用程式的主要進入點。
///
[STAThread]
static void Main()
{
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new Form1());
xml();
}
static void xml()
{
//建立時間放在檔名
DateTime dt = DateTime.Now;
string time = string.Format("{0:yyyyMMddHHmmssffff}", dt);
//新增第一個xml檔
XmlDocument doc = new XmlDocument();
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(xmlDeclaration);
XmlElement rootElement = doc.CreateElement("Company1");
doc.AppendChild(rootElement);
//新增資料
XmlElement childElement = doc.CreateElement("Employee");
XmlAttribute childAtrbt = doc.CreateAttribute("Department");
childAtrbt.Value = "研發部";
childElement.Attributes.Append(childAtrbt);
rootElement.AppendChild(childElement);
doc.Save(@"C:\Users\user\Desktop\test\" + "test_" + time + ".xml");
//////////////////////////////////////////////////////////////////////////////////////
//新增第二個xml檔
XmlDocument doc2 = new XmlDocument();
XmlDeclaration xmlDeclaration2 = doc2.CreateXmlDeclaration("1.0", "UTF-8", null);
doc2.AppendChild(xmlDeclaration2);
XmlElement rootElement2 = doc2.CreateElement("Company2");
doc2.AppendChild(rootElement2);
//將第一個xml檔最後的節點複製到第二個xml檔
XmlNode newNode = doc2.ImportNode(doc.DocumentElement.LastChild, true);
doc2.DocumentElement.AppendChild(newNode);
doc2.Save(@"C:\Users\user\Desktop\test\" + "test.copy_" + time + ".xml");
}
}
}
test_201311201933485572.xml
-
test.copy_201311201933485572.xml
-













