0
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();

如果必须将节点作为根节点的子节点插入,则上面的代码运行良好。但我想将节点作为任何其他节点的子节点插入。我该怎么办?

4

1 回答 1

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 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");
于 2012-09-10T04:48:11.830 回答