简体   繁体   中英

How to merge two XML files with certain condition using StAX

For example, let's say we have the two XML files:

"1.xml"

<School>
   <Stdent id="1">
      <Name>Jhon</Name>
      <Age>12</Age>
      <Grade>7</Grade>
   </Student>
   <Stdent id="2">
      <Name>Mike</Name>
      <Age>11</Age>
      <Grade>8</Grade>
   </Student>
</School>

"2.xml"

<School>
   <Stdent id="1">
      <Name>Jhon</Name>
      <Age>13</Age>
      <Grade>9</Grade>
   </Student>
   <Stdent id="3">
      <Name>Ann</Name>
      <Age>11</Age>
      <Grade>10</Grade>
    </Student>
</School>

For the merged file the condition is if the student id in the second file matches one in the first file put it from the second file. The merged file should look like this:

"merge.xml"

<School>
   <Stdent id="1">
      <Name>Jhon</Name>
      <Age>13</Age>
      <Grade>9</Grade>
   </Student>
   <Stdent id="2">
      <Name>Mike</Name>
      <Age>11</Age>
      <Grade>8</Grade>
   </Student>
   <Stdent id="3">
      <Name>Ann</Name>
      <Age>11</Age>
      <Grade>10</Grade>
    </Student>
</School>

How should I do it? Thanks in advance!

If you're flexible about the technology you can use, here's the XSLT 3.0 solution:

<xsl:merge>
  <xsl:merge-source for-each-source="'xml1.xml', 'xml2.xml'"
                    select="//Stdent">
    <xsl:merge-key select="@id"/>
  </xsl:merge-source>
  <xsl:merge-action>
    <xsl:copy-of select="current-merge-group()[last()]"/>
  </xsl:merge-action>
</xsl:merge>

Your question is tagged with Java, so I'm assuming it's what you're using.

There are two ways to go about it, one is with JAXB - which is a standard Java library facilitating mapping of XML to and from Java objects. Your files look structured, so that's what I would recommend. You can create a model class based on your XML and use this library to convert your files to a Java object. You can also generate a schema based on the XML files and pass that schema to the JAXB and it will generate the model classes for you.

The second option is to parse the files using the DocumentBuilder class and manually insert nodes.

Both of these tools are well-documented and can be easily looked up online so I will not paste code examples.

I would not recommend the XSLT approach that someone else suggested for something that simple. XSLT is hard to read and maintain, and not that commonly used. Manipulating XMLs programmatically is bound to come handy at some point anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM