开发者

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:

  1. The order of elements matte开发者_开发知识库rs;
  2. The name-value pair of attributes is important, but the order of attributes is NOT;
  3. 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:

  1. Maintain element order
  2. Order the attributes of each element (e.g. alphabetize based on the attribute name)
  3. 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

  1. Use a DOM parser to produce a DOM tree
  2. Normalize the DOM tree according to your rules
  3. 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜