XML_Vergleich

Sara456

Mitglied
Hallo Java-Gemeinde,

ich versuche xml zu vergleichen. Habe ein Beispiel aus dem Internet gefunden. Nun habe Schwierigkeiten das Beispiel zu verwenden. Muss ich für den Vergleich Methoden verwenden?
Code:
 import java.io.ByteArrayInputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public class XmlDiff 
{
    private boolean nodeTypeDiff = true;
    private boolean nodeValueDiff = true;
    String xml1 = "<Ochs><Name>Meier</Name></Ochs>";
	 String xml2 = "<Ochs><Name>Meier</Name></Ochs>";
    public boolean diff( String xml1, String xml2, List<String> diffs ) throws Exception
    {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setCoalescing(true);
        dbf.setIgnoringElementContentWhitespace(true);
        dbf.setIgnoringComments(true);
        DocumentBuilder db = dbf.newDocumentBuilder();


        Document doc1 = db.parse(new ByteArrayInputStream(xml1.getBytes()));
        Document doc2 = db.parse(new ByteArrayInputStream(xml2.getBytes()));

        doc1.normalizeDocument();
        doc2.normalizeDocument();

        return diff( doc1, doc2, diffs );

    }

    /**
     * Diff 2 nodes and put the diffs in the list 
     */
    public boolean diff( Node node1, Node node2, List<String> diffs ) throws Exception
    {
        if( diffNodeExists( node1, node2, diffs ) )
        {
            return true;
        }

        if( nodeTypeDiff )
        {
            diffNodeType(node1, node2, diffs );
        }

        if( nodeValueDiff )
        {
            diffNodeValue(node1, node2, diffs );
        }


        System.out.println(node1.getNodeName() + "/" + node2.getNodeName());

        diffAttributes( node1, node2, diffs );
        diffNodes( node1, node2, diffs );

        return diffs.size() > 0;
    }

    /**
     * Diff the nodes
     */
    public boolean diffNodes( Node node1, Node node2, List<String> diffs ) throws Exception
    {
        //Sort by Name
        Map<String,Node> children1 = new LinkedHashMap<String,Node>();      
        for( Node child1 = node1.getFirstChild(); child1 != null; child1 = child1.getNextSibling() )
        {
            children1.put( child1.getNodeName(), child1 );
        }

        //Sort by Name
        Map<String,Node> children2 = new LinkedHashMap<String,Node>();      
        for( Node child2 = node2.getFirstChild(); child2!= null; child2 = child2.getNextSibling() )
        {
            children2.put( child2.getNodeName(), child2 );
        }

        //Diff all the children1
        for( Node child1 : children1.values() )
        {
            Node child2 = children2.remove( child1.getNodeName() );
            diff( child1, child2, diffs );
        }

        //Diff all the children2 left over
        for( Node child2 : children2.values() )
        {
            Node child1 = children1.get( child2.getNodeName() );
            diff( child1, child2, diffs );
        }

        return diffs.size() > 0;
    }


    /**
     * Diff the nodes
     */
    public boolean diffAttributes( Node node1, Node node2, List<String> diffs ) throws Exception
    {        
        //Sort by Name
        NamedNodeMap nodeMap1 = node1.getAttributes();
        Map<String,Node> attributes1 = new LinkedHashMap<String,Node>();        
        for( int index = 0; nodeMap1 != null && index < nodeMap1.getLength(); index++ )
        {
            attributes1.put( nodeMap1.item(index).getNodeName(), nodeMap1.item(index) );
        }

        //Sort by Name
        NamedNodeMap nodeMap2 = node2.getAttributes();
        Map<String,Node> attributes2 = new LinkedHashMap<String,Node>();        
        for( int index = 0; nodeMap2 != null && index < nodeMap2.getLength(); index++ )
        {
            attributes2.put( nodeMap2.item(index).getNodeName(), nodeMap2.item(index) );

        }

        //Diff all the attributes1
        for( Node attribute1 : attributes1.values() )
        {
            Node attribute2 = attributes2.remove( attribute1.getNodeName() );
            diff( attribute1, attribute2, diffs );
        }

        //Diff all the attributes2 left over
        for( Node attribute2 : attributes2.values() )
        {
            Node attribute1 = attributes1.get( attribute2.getNodeName() );
            diff( attribute1, attribute2, diffs );
        }

        return diffs.size() > 0;
    }
    /**
     * Check that the nodes exist
     */
    public boolean diffNodeExists( Node node1, Node node2, List<String> diffs ) throws Exception
    {
        if( node1 == null && node2 == null )
        {
            diffs.add( getPath(node2) + ":node " + node1 + "!=" + node2 + "\n" );
            return true;
        }

        if( node1 == null && node2 != null )
        {
            diffs.add( getPath(node2) + ":node " + node1 + "!=" + node2.getNodeName() );
            return true;
        }

        if( node1 != null && node2 == null )
        {
            diffs.add( getPath(node1) + ":node " + node1.getNodeName() + "!=" + node2 );
            return true;
        }

        return false;
    }

    /**
     * Diff the Node Type
     */
    public boolean diffNodeType( Node node1, Node node2, List<String> diffs ) throws Exception
    {       
        if( node1.getNodeType() != node2.getNodeType() ) 
        {
            diffs.add( getPath(node1) + ":type " + node1.getNodeType() + "!=" + node2.getNodeType() );
            return true;
        }

        return false;
    }

    /**
     * Diff the Node Value
     */
    public boolean diffNodeValue( Node node1, Node node2, List<String> diffs ) throws Exception
    {       
        if( node1.getNodeValue() == null && node2.getNodeValue() == null )
        {
            return false;
        }

        if( node1.getNodeValue() == null && node2.getNodeValue() != null )
        {
            diffs.add( getPath(node1) + ":type " + node1 + "!=" + node2.getNodeValue() );
            return true;
        }

        if( node1.getNodeValue() != null && node2.getNodeValue() == null )
        {
            diffs.add( getPath(node1) + ":type " + node1.getNodeValue() + "!=" + node2 );
            return true;
        }

        if( !node1.getNodeValue().equals( node2.getNodeValue() ) )
        {
            diffs.add( getPath(node1) + ":type " + node1.getNodeValue() + "!=" + node2.getNodeValue() );
            return true;
        }

        return false;
    }


    /**
     * Get the node path
     */
    public String getPath( Node node )
    {
        StringBuilder path = new StringBuilder();

        do
        {           
            path.insert(0, node.getNodeName() );
            path.insert( 0, "/" );
        }
        while( ( node = node.getParentNode() ) != null );

        return path.toString();
    }
}

Viele Grüße

Sara
 
Hi
kannst du deine Frage bitte noch mal verständlich stellen?
Methoden wirst du wohl verwenden müssen, weil Java-Programme immer daraus aufgebaut sind…
 
Ich nehme an, Sara meint welche der Routinenen soll sie denn für di eVerarbeitung aufrufen.
Jo also da würde ich kurz rübergeschaut ,die oberste vorschlagen. Die sieht mir aus als die übergeornete, oder irre ich mich da jetzt?

Takidoso
 
Hallo,

hab da mal was gebastelt :D. Der Vergleich funktioniert auch.
Code:
public class Vergleich {
	 static String a= "<Daten> <Name>Sara</Name><Datum>25.04.2013</Datum></Daten>";
	 static String b= "<Daten> <Name>Sara</Name><Datum>25.03.2013</Datum></Daten>";
	    	public static void main(String[] args){
	    	    try {
	    	    	
	    	    	
		            Diff diff = new Diff(a, b);
		              System.out.println("Ähnlich? " + diff.similar());
		            System.out.println("Identisch? " + diff.identical());
		 
		            DetailedDiff detDiff = new DetailedDiff(diff);
		            List differences = detDiff.getAllDifferences();
		            for (Object object : differences) {
		                Difference difference = (Difference)object;
		                System.out.println("***********************");
		                System.out.println(difference);
		                System.out.println("***********************");
		            }
		 
		        } catch (SAXException e) {
		            e.printStackTrace();
		        } catch (IOException e) {
		            e.printStackTrace();
	    	}
	        
	    }}


Ich würde noch gerne etwas ergänzen, und zwar möchte ich dass das Datum beim Vergleich ignoriert wird.
Code:
<Datum>25.04.2013</Datum>
Das Tag Datum soll ignoriert werden. Wie kann ich das realisieren?
Kennt sich einer damit aus.

Viele Grüße

Sara
 
schau doch mal ob du von den "Node"- Objekten das Tag auslesen kannst. dann kannst Du danach in einer Fallunterscheidung dein Feld Ignorieren.
Falls Du mehrere Datumsfelder haben solltest, die aber nicht alle ingoriert weden sollten, scheint mir die getPathroutine in deiner Programmcodekopie Hilfreich ;-)
 
Wie ich Dir schon sagte, shau doch mal auf den Code den Du Dir kopiert hatest. Unterswuche die Objekte.
Falls Du nicht mit einer IDE, sondern nur mit einem Editor und dem nakten Compile bewaffnet bist, empfehle ich Dir z.B. Eclipse als IDE.
da kannst Du ganz bequem Objekte, bw Klassen untersuchen, was sie so können etc.

Viel Spaß

Takidoso
 
Hallo,

ich habe es hingekriegt, dass Tags ignoriert werden. Meine Frage ist jetzt, wenn ich mehrere Tags habe mit den gleichen Namen wie kann ich nur einen dieser Tags ignorieren? Ich habe zwei Tags mit dem Name Inhalt, aber ich will nur einen Ignorien , und das mit dem Datum. Momentan werden alle Tags, die Inhalt sind ignoriert. Ich möchte, dass
Code:
<Inhalt="Datum">
ignoriert wird.
Code:
String a = "<root><elements><Inhalt ="Name">Sara</Inhalt><Inhalt="Datum">29.04.2013</Inhalt></elements></root>";
  String b =  "<root><elements><Inhalt ="Name">Sara</Inhalt><Inhalt="Datum">26.04.2013</Inhalt></elements></root>";


Code:
import java.io.IOException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;


import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.Difference;
import org.custommonkey.xmlunit.DifferenceConstants;
import org.custommonkey.xmlunit.DifferenceListener;
import org.custommonkey.xmlunit.XMLUnit;
import org.w3c.dom.Node;


public final class QueryResultsComparator {

	 public static void main(String[] args) throws Exception{
        String a = "<root><elements><Inhalt ="Name">Sara</Inhalt><Inhalt="Datum">29.04.2013</Inhalt></elements></root>";
        String b =  "<root><elements><Inhalt ="Name">Sara</Inhalt><Inhalt="Datum">26.04.2013</Inhalt></elements></root>";
        XMLUnit.setNormalizeWhitespace(true);
        Diff diff = new Diff(a, b);
        diff.overrideDifferenceListener(new MyDifferenceLister());
         if (!diff.identical()) {
         DetailedDiff ddiff = new DetailedDiff(diff);
         List<Difference> diffs = ddiff.getAllDifferences();
         for (Difference d : diffs) {
         System.out.println(d);
         }
         }
    }

   
 
    private static class MyDifferenceLister implements DifferenceListener {
        private List<Difference> ignore;

        MyDifferenceLister() {
            ignore = new LinkedList<Difference>();
            ignore.add(DifferenceConstants.HAS_DOCTYPE_DECLARATION);
            ignore.add(DifferenceConstants.NAMESPACE_PREFIX);
            ignore.add(DifferenceConstants.CHILD_NODELIST_SEQUENCE);
            ignore.add(DifferenceConstants.CHILD_NODELIST_LENGTH);
            ignore.add(DifferenceConstants.ATTR_SEQUENCE);
            ignore.add(DifferenceConstants.COMMENT_VALUE);
        }

        public int differenceFound(Difference difference) {
           
            if (difference.equals(DifferenceConstants.CHILD_NODE_NOT_FOUND)
                    && "Inhalt".equals(difference.getTestNodeDetail().getValue())) {
                return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
            }
       
            if (difference.equals(DifferenceConstants.TEXT_VALUE)
                    && "Inhalt".equals(difference.getTestNodeDetail().getNode().getParentNode().getNodeName())) {
                return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
            }
           
            
            return ignore.contains(difference) ? RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL : RETURN_ACCEPT_DIFFERENCE;
        }

      
        public void skippedComparison(Node n1, Node n2) {
        }
    }
}

LG Sara
 
Hab einen Fehler es ist nicht <Inhalt="Datum">
Code:
<Inhalt Name="Datum">
Wie kann ich es ignorieren. Ich komme nicht weiter :(
 
Hallo,

ich habe es hingekriegt, dass Tags ignoriert werden. Meine Frage ist jetzt, wenn ich mehrere Tags habe mit den gleichen Namen wie kann ich nur einen dieser Tags ignorieren? Ich habe zwei Tags mit dem Name Inhalt, aber ich will nur einen Ignorien , und das mit dem Datum. Momentan werden alle Tags, die Inhalt sind ignoriert. Ich möchte, dass
Code:
<Inhalt="Datum">
ignoriert wird.
Code:
String a = "<root><elements><Inhalt ="Name">Sara</Inhalt><Inhalt="Datum">29.04.2013</Inhalt></elements></root>";
  String b =  "<root><elements><Inhalt ="Name">Sara</Inhalt><Inhalt="Datum">26.04.2013</Inhalt></elements></root>";


Code:
import java.io.IOException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;


import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.Difference;
import org.custommonkey.xmlunit.DifferenceConstants;
import org.custommonkey.xmlunit.DifferenceListener;
import org.custommonkey.xmlunit.XMLUnit;
import org.w3c.dom.Node;


public final class QueryResultsComparator {

	 public static void main(String[] args) throws Exception{
        String a = "<root><elements><Inhalt ="Name">Sara</Inhalt><Inhalt="Datum">29.04.2013</Inhalt></elements></root>";
        String b =  "<root><elements><Inhalt ="Name">Sara</Inhalt><Inhalt="Datum">26.04.2013</Inhalt></elements></root>";
        XMLUnit.setNormalizeWhitespace(true);
        Diff diff = new Diff(a, b);
        diff.overrideDifferenceListener(new MyDifferenceLister());
         if (!diff.identical()) {
         DetailedDiff ddiff = new DetailedDiff(diff);
         List<Difference> diffs = ddiff.getAllDifferences();
         for (Difference d : diffs) {
         System.out.println(d);
         }
         }
    }

   
 
    private static class MyDifferenceLister implements DifferenceListener {
        private List<Difference> ignore;

        MyDifferenceLister() {
            ignore = new LinkedList<Difference>();
            ignore.add(DifferenceConstants.HAS_DOCTYPE_DECLARATION);
            ignore.add(DifferenceConstants.NAMESPACE_PREFIX);
            ignore.add(DifferenceConstants.CHILD_NODELIST_SEQUENCE);
            ignore.add(DifferenceConstants.CHILD_NODELIST_LENGTH);
            ignore.add(DifferenceConstants.ATTR_SEQUENCE);
            ignore.add(DifferenceConstants.COMMENT_VALUE);
        }

        public int differenceFound(Difference difference) {
           
            if (difference.equals(DifferenceConstants.CHILD_NODE_NOT_FOUND)
                    && "Inhalt".equals(difference.getTestNodeDetail().getValue())) {
                return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
            }
       
            if (difference.equals(DifferenceConstants.TEXT_VALUE)
                    && "Inhalt".equals(difference.getTestNodeDetail().getNode().getParentNode().getNodeName())) {
                return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
            }
           
            
            return ignore.contains(difference) ? RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL : RETURN_ACCEPT_DIFFERENCE;
        }

      
        public void skippedComparison(Node n1, Node n2) {
        }
    }
}

LG Sara

Du hast eine getPath-Rouine in Deinem Beispiel-Programm, vielleicht hilft sie Dir ja weiter ;-)
 
Zurück