How to combine XML files?

I have two xml files that have the same schema, and I would like to merge into one XML file. Is there an easy way to do this?

For instance,

<Root>
    <LeafA>
        <Item1 />
        <Item2 />
    </LeafA>
    <LeafB>
        <Item1 />
        <Item2 />
    </LeafB>
</Root>

+

<Root>
    <LeafA>
        <Item3 />
        <Item4 />
    </LeafA>
    <LeafB>
        <Item3 />
        <Item4 />
    </LeafB>
</Root>

= new file containing

<Root>
    <LeafA>
        <Item1 />
        <Item2 />
        <Item3 />
        <Item4 />
    </LeafA>
    <LeafB>
        <Item1 />
        <Item2 />
        <Item3 />
        <Item4 />
    </LeafB>
</Root>
+5
source share
6 answers

“Auto-merge XML” sounds like a relatively simple requirement, but when you go into all the details, it gets pretty complicated. Merging with C # or XSLT will be much simpler for a more specific task, for example, in the answer for the EF model. Using tools for manual merging can also be an option (see this SO question ).

( ) Java: XML

. - : 2 ( , , ); , XML ..

,

  • , ,
  • XML-.

.

// determine which elements we consider the same
//
private static bool AreEquivalent(XElement a, XElement b)
{
    if(a.Name != b.Name) return false;
    if(!a.HasAttributes && !b.HasAttributes) return true;
    if(!a.HasAttributes || !b.HasAttributes) return false;
    if(a.Attributes().Count() != b.Attributes().Count()) return false;

    return a.Attributes().All(attA => b.Attributes(attA.Name)
        .Count(attB => attB.Value == attA.Value) != 0);
}

// Merge "merged" document B into "source" A
//
private static void MergeElements(XElement parentA, XElement parentB)
{
    // merge per-element content from parentB into parentA
    //
    foreach (XElement childB in parentB.DescendantNodes())
    {
        // merge childB with first equivalent childA
        // equivalent childB1, childB2,.. will be combined
        //
        bool isMatchFound = false;
        foreach (XElement childA in parentA.Descendants())
        {
            if (AreEquivalent(childA, childB))
            {
                MergeElements(childA, childB);
                isMatchFound = true;
                break;
            }
        }

        // if there is no equivalent childA, add childB into parentA
        //
        if (!isMatchFound) parentA.Add(childB);
    }
}

XML, XML , ... :

public static void Test()
{
    var a = XDocument.Parse(@"
    <Root>
        <LeafA>
            <Item1 />
            <Item2 />
            <SubLeaf><X/></SubLeaf>
        </LeafA>
        <LeafB>
            <Item1 />
            <Item2 />
        </LeafB>
    </Root>");
    var b = XDocument.Parse(@"
    <Root>
        <LeafB>
            <Item5 />
            <Item1 />
            <Item6 />
        </LeafB>
        <LeafA Name=""X"">
            <Item3 />
        </LeafA>
        <LeafA>
            <Item3 />
        </LeafA>
        <LeafA>
            <SubLeaf><Y/></SubLeaf>
        </LeafA>
    </Root>");

    MergeElements(a.Root, b.Root);
    Console.WriteLine("Merged document:\n{0}", a.Root);
}

, , B:

<Root>
  <LeafA>
    <Item1 />
    <Item2 />
    <SubLeaf>
      <X />
      <Y />
    </SubLeaf>
    <Item3 />
  </LeafA>
  <LeafB>
    <Item1 />
    <Item2 />
    <Item5 />
    <Item6 />
  </LeafB>
  <LeafA Name="X">
    <Item3 />
  </LeafA>
</Root>
+10

, :

, .

Linux head tail, .

+1

XSLT, - ( a.xml):

<xsl:variable name="docB" select="document('b.xml')"/>
<xsl:template match="Root">
  <Root><xsl:apply-templates/></Root>
</xsl:template>
<xsl:template match="Root/LeafA">
   <xsl:copy-of select="*"/>
   <xsl:copy-of select="$docB/Root/LeafA/*"/>
</xsl:template>
<xsl:template match="Root/LeafB">
   <xsl:copy-of select="*"/>
   <xsl:copy-of select="$docB/Root/LeafB/*"/>
</xsl:template>
+1

vimdiff file_a file_b

BeyondCompare , windows http://www.scootersoftware.com/

0

# script. , , , , , XML.

script :

var a = new XmlDocument();
a.Load(PathToFile1);

var b = new XmlDocument();
b.Load(PathToFile2);

MergeNodes(
    a.SelectSingleNode(nodePath),
    b.SelectSingleNode(nodePath).ChildNodes,
    a);

a.Save(PathToFile1);

MergeNodes() :

private void MergeNodes(XmlNode parentNodeA, XmlNodeList childNodesB, XmlDocument parentA)
{
    foreach (XmlNode oNode in childNodesB)
    {
        // Exclude container node
        if (oNode.Name == "#comment") continue;

        bool isFound = false;
        string name = oNode.Attributes["Name"].Value;

        foreach (XmlNode child in parentNodeA.ChildNodes)
        {
            if (child.Name == "#comment") continue;

            // If node already exists and is unchanged, exit loop
            if (child.OuterXml== oNode.OuterXml&& child.InnerXml == oNode.InnerXml)
            {
                isFound = true;
                Console.WriteLine("Found::NoChanges::" + oNode.Name + "::" + name);
                break;
            }

            // If node already exists but has been changed, replace it
            if (child.Attributes["Name"].Value == name)
            {
                isFound = true;
                Console.WriteLine("Found::Replaced::" + oNode.Name + "::" + name);
                parentNodeA.ReplaceChild(parentA.ImportNode(oNode, true), child);
            }
        }

        // If node does not exist, add it
        if (!isFound)
        {
            Console.WriteLine("NotFound::Adding::" + oNode.Name + "::" + name);
            parentNodeA.AppendChild(parentA.ImportNode(oNode, true));
        }
    }
}

- , , , XML, :)

, , edmx Entity Framework, SSDL, CDSL MSL.

0

How could you do this, load the dataset using xml and merge the data.

    Dim dsFirst As New DataSet()
    Dim dsMerge As New DataSet()

    ' Create new FileStream with which to read the schema.
    Dim fsReadXmlFirst As New System.IO.FileStream(myXMLfileFirst, System.IO.FileMode.Open)
    Dim fsReadXmlMerge As New System.IO.FileStream(myXMLfileMerge, System.IO.FileMode.Open)

    Try
        dsFirst.ReadXml(fsReadXmlFirst)

        dsMerge.ReadXml(fsReadXmlMerge)

        Dim str As String = "Merge Table(0) Row Count = " & dsMerge.Tables(0).Rows.Count
        str = str & Chr(13) & "Merge Table(1) Row Count = " & dsMerge.Tables(1).Rows.Count
        str = str & Chr(13) & "Merge Table(2) Row Count = " & dsMerge.Tables(2).Rows.Count

        MsgBox(str)

        dsMerge.Merge(dsFirst, True)

        DataGridParent.DataSource = dsMerge
        DataGridParent.DataMember = "rulefile"

        DataGridChild.DataSource = dsMerge
        DataGridChild.DataMember = "rule"

        str = ""
        str = "Merge Table(0) Row Count = " & dsMerge.Tables(0).Rows.Count
        str = str & Chr(13) & "Merge Table(1) Row Count = " & dsMerge.Tables(1).Rows.Count
        str = str & Chr(13) & "Merge Table(2) Row Count = " & dsMerge.Tables(2).Rows.Count

        MsgBox(str)
0
source

All Articles