How to create checksum for an XML file in Java
I need to create a checksum for an XML file in Java. The basic requirements are:
- The order of elements matte开发者_开发知识库rs;
- The name-value pair of attributes is important, but the order of attributes is NOT;
- Ignore all white spaces and comments
Anyone can provide any hint or sample code?
Thanks, Mark
You can make use of the Java Digital XML Signature APIs:
Introduction to the Java Digital XML Signature APIs
Method 1: Use XSLT to normalize the document.
Essentially you would use XSLT to normalize XML documents so that equivalent documents distill down into the same document. The transformation would:
- Maintain element order
- Order the attributes of each element (e.g. alphabetize based on the attribute name)
- Strip the whitespace and comments
You would then checksum the normalized version of the document.
Some useful references:
- XSLT Tutorial - https://stackoverflow.com/questions/1858345/xsltwhich-is-the-best-tutorial-you-would-like-to-recommend
- Identity transformation as a starting point - XSL That Returns the XML unchanged
- Sort attributes - Using XSL to sort attributes
normalize-space()
- how to get the normalize-space() xpath function to work?
Method 2. Use a DOM parser
- Use a DOM parser to produce a DOM tree
- Normalize the DOM tree according to your rules
- Traverse the tree and feed the XML items to a checksum calculator
Method 3. Use a SAX or StAX parser
If you don't like the intermediate step of producing a normalized document or DOM tree, you could use SAX or StAX to parse the XML to maintain/order/strip like above on the fly and feed each element/content/attribute/value/etc to a checksum calculator.
check the standard W3C standard 'c14n'. + ignor whitespace. It will even handle the namespaces. For sure in you libarry you have an implemntation
精彩评论