在C#中合并配置文件(或XML)

时间:2021-10-09 00:25:57

What would be the fastest way, to merge 2 XML files, so I would locate a node in first one, empty it, take all children from the same tag (same node) in second XML and put it in the first one.

合并2个XML文件的最快方法是什么,所以我会在第一个节点中找到一个节点,清空它,从第二个XML中取出同一个标签(同一节点)中的所有子节点并将其放在第一个节点中。

2 个解决方案

#1


4  

You can load both files into two XElement objects, locate the target nodes in both objects and do the switch.

您可以将两个文件加载到两个XElement对象中,在两个对象中找到目标节点并执行切换。

Here is a sample:

这是一个示例:

var nodes1 = XDocument.Parse(file1).Element("test").Element("nodes");
var nodes2 = XDocument.Parse(file2).Element("test").Element("nodes");

nodes1.Nodes().Remove();
nodes1.Add(nodes2.Nodes());

Here is the XML snippet i tried it on:

这是我试过的XML片段:

<test>
    <nodes>
        <node id="1">
            Hi
        </node>
        <node id="2">
            Hi again
        </node>
        <node id="3">
            Hi once more
        </node>
    </nodes>
</test>

#2


0  

Check out this article on MSDN: Article

在MSDN上查看这篇文章:文章

I think this is the bit of code you are looking for:

我认为这是您正在寻找的一些代码:

try
{
    XmlTextReader xmlreader1 = new XmlTextReader("C:\\Books1.xml");
    XmlTextReader xmlreader2 = new XmlTextReader("C:\\Books2.xml");

    DataSet ds = new DataSet();
    ds.ReadXml(xmlreader1);
    DataSet ds2 = new DataSet();
    ds2.ReadXml(xmlreader2);
    ds.Merge(ds2);
    ds.WriteXml("C:\\Books.xml");
    Console.WriteLine("Completed merging XML documents");
}
catch (System.Exception ex)
{
    Console.Write(ex.Message);
}
Console.Read(); 

Hope that helps!

希望有所帮助!

#1


4  

You can load both files into two XElement objects, locate the target nodes in both objects and do the switch.

您可以将两个文件加载到两个XElement对象中,在两个对象中找到目标节点并执行切换。

Here is a sample:

这是一个示例:

var nodes1 = XDocument.Parse(file1).Element("test").Element("nodes");
var nodes2 = XDocument.Parse(file2).Element("test").Element("nodes");

nodes1.Nodes().Remove();
nodes1.Add(nodes2.Nodes());

Here is the XML snippet i tried it on:

这是我试过的XML片段:

<test>
    <nodes>
        <node id="1">
            Hi
        </node>
        <node id="2">
            Hi again
        </node>
        <node id="3">
            Hi once more
        </node>
    </nodes>
</test>

#2


0  

Check out this article on MSDN: Article

在MSDN上查看这篇文章:文章

I think this is the bit of code you are looking for:

我认为这是您正在寻找的一些代码:

try
{
    XmlTextReader xmlreader1 = new XmlTextReader("C:\\Books1.xml");
    XmlTextReader xmlreader2 = new XmlTextReader("C:\\Books2.xml");

    DataSet ds = new DataSet();
    ds.ReadXml(xmlreader1);
    DataSet ds2 = new DataSet();
    ds2.ReadXml(xmlreader2);
    ds.Merge(ds2);
    ds.WriteXml("C:\\Books.xml");
    Console.WriteLine("Completed merging XML documents");
}
catch (System.Exception ex)
{
    Console.Write(ex.Message);
}
Console.Read(); 

Hope that helps!

希望有所帮助!