XmlTextReader myReader = new XmlTextReader("abc.xml");
XmlDocument mySourceDoc = new XmlDocument();
mySourceDoc.Load(myReader);
myReader.Close();
myReader = new XmlTextReader("pqr.xml");
XmlDocument myDestDoc = new XmlDocument();
myDestDoc.Load(myReader);
myReader.Close();
XmlNode rootDest = myDestDoc["root node"];
XmlElement nodeOrig = (XmlElement)mySourceDoc["root node"].ChildNodes[0];
XmlNode nodeDest = myDestDoc.ImportNode(nodeOrig, true);
try
{
rootDest.AppendChild(nodeDest);
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
XmlTextWriter myWriter = new XmlTextWriter("pqr.xml", Encoding.UTF8);
myWriter.Formatting = Formatting.Indented;
myDestDoc.WriteTo(myWriter);
myWriter.Close();
如果节点必须作为根节点的子节点插入,上面的代码很有效。但我想插入节点作为任何其他节点的子节点。我该怎么办?
答案 0 :(得分:0)
说,你有以下xml:
<CONFIGURATION>
<File>D:\Test\TestFolder\TestFolder1\TestFile.txt</File>
<Dir>D:\Test\TestFolder\TestFolder1\</Dir>
<File>D:\Test\TestFolder\TestFolder2\TestFile02.txt</File>
<File>D:\Test\TestFolder\TestFolder2\TestFile04.txt</File>
<Dir>D:\Test\TestFolder\TestFolder2\</Dir>
</CONFIGURATION>
你想要创建一个新的,只包含 File 节点;根节点也必须被称为 Files 。这样的xml看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<Files>
<File>D:\Test\TestFolder\TestFolder1\TestFile.txt</File>
<File>D:\Test\TestFolder\TestFolder2\TestFile02.txt</File>
<File>D:\Test\TestFolder\TestFolder2\TestFile04.txt</File>
</Files>
以下代码执行此操作:
XElement infile = XElement.Load("In.xml");
XElement outfile = new XElement("Files");
foreach (XElement x in infile.Elements("File"))
outfile.Add(x);
outfile.Save("Out.xml");
这是一个简单的示例,如何使用LINQ To XML将节点从一个xml文档传输到另一个xml文档。考虑使用它。
你应该喜欢它。
修改强>
原始xml:
<?xml version="1.0" encoding="utf-8"?>
<root>
<abc>
<pdf>hhh</pdf>
</abc>
</root>
用户输入:
abc#uuu#ttt
输出xml:
<?xml version="1.0" encoding="utf-8"?>
<root>
<abc>
<pdf>hhh</pdf>
<uuu>ttt</uuu>
</abc>
</root>
代码:
string userinput = "abc#uuu#ttt";
XElement infile = XElement.Load("In.xml");
XElement temp = infile;
string[] commands = userinput.Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < commands.Length; i++)
{
if (i + 1 == commands.Length)
temp.Value = commands[i];
else
{
if (temp.Element(commands[i]) == null)
temp.Add(new XElement(commands[i]));
temp = temp.Element(commands[i]);
}
}
infile.Save("Out.xml");