views:

143

answers:

1

I need to know. Is there some javascript implementation exist to handle deltas between XML data ? So main point is to detect difference existence, it doesn't matter what was changed: attribute or node value.

Requirements are following:

  • each node will have unique id (it's one of simplifications made to find more candidates-libraries)
  • deltas should be checked in nodes, attributes and node values
  • support XML node hierarchies up to 3 levels
  • the result of computation should be also XML (see example), but it could be 3 arrays of added, updated and deleted nodes
  • ignore some subnodes in delta calculation, for example I want to track just 3 levels of hierarchy, not more
  • changes detection should not be propogated to upper nodes, so for example child node changes should not make parent node as updated

Here is example how it should work:
XML#1:

<node id="0">
  <node id="1">
     <node id="4">
       <node id="23">DATA</data>
     </node>
     <node id="5">DATA</node>
  </node>  
</node>

XML#2:

<node id="0">
  <node id="1">
     <node id="3">
        <node id="342">DATA</data>
     </node>
     <node id="5" some_attribute="attr"/>
  </node>  
  <node id="6"/>
</node >

So result should be following:

<result>
   <added>
      <id>6</id>
      <id>3</id> 
      <id>342</id> 
   </added>
   <updated>
      <id>5</id>
   </updated>
   <removed>
      <id>4</id>
      <id>23</id>
   </removed>
</result>
A: 

I'm not a big user of XSLT, but I'm sure you could use it to achieve what you're trying to do if you're familiar with it. Maybe you should try adding the tag to the question.

The following XSLT document, taken from http://msdn.microsoft.com/en-us/magazine/cc164169.aspx, will supposedly merge two documents but I doubt it would be as thorough as you want it to:

<xsl:transform version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
  <xsl:template match="/">
    <Container>
      <xsl:copy-of select="document('product.xml')"/>
      <xsl:copy-of select="document('material.xml')"/>        
    </Container>
  </xsl:template>
</xsl:stylesheet>

The examples on that page are for .NET, but Internet Explorer has access to many MSXML ActiveX controls that might provide the functions you need if cross-browser compatibility isn't a requirement.

Andy E
I'd +1 if the OP was ok with XSLT, merges being a fairly common and googleable use-case for XSLT.
annakata
True. Another way of doing it would be to loop through each node and attribute in XMLFile1 and then run a XMLFile2.selectSingleNode() passing the XPath expression of the node or attribute to check if it exists, then using an === on the nodevalues to see if they are different, and write the result to a third XML file as described above. I only wish I had the time to write it :-)
Andy E
Sorry but cross-browser compatibility is strong requirement. Server side development for XSLT templates is out of context.
Pavel Rodionov