1

I am looking for an implementation of org.w3c.dom.Node for data types other than XML, like json or avro. This will allow me to reuse functionalities written against org.w3c.dom.Node, such as xpath.

org.w3c.dom.Node document = new JsonDocument(myJsonMessage);

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();

String msg = xpath.evaluate("/document/element", document);

msg is an evaluation of xpath against a json document, provided I have an implementation of Node/Document for Json.

Pieter
  • 895
  • 11
  • 22
Johan Witters
  • 1,529
  • 11
  • 23
  • See also [Is there a SaxParser that reads json and fires events so it looks like xml](https://stackoverflow.com/questions/4373233/is-there-a-saxparser-that-reads-json-and-fires-events-so-it-looks-like-xml) – Vadzim Jun 04 '19 at 20:55

2 Answers2

0

The simplest solution may be to convert your JSON document to XML then use your existing functionality to perform xpath queries.

Convert JSON to XML

AdamPillingTech
  • 456
  • 2
  • 7
  • @PhilHead,thanks for your feedback. I can see that would work, however, I can't afford converting json to xml. – Johan Witters Dec 18 '17 at 12:00
  • I don't think there is an "out of the box" implementation of Node that will give you what you desire. It is an interface, however, so you could feasibly create your own implementation which delegates to something like JSONPath https://stackoverflow.com/questions/8481380/is-there-a-json-equivalent-of-xquery-xpath – AdamPillingTech Dec 18 '17 at 13:34
0

org.w3c.dom.Node is an interface. I ended up writing implementations of the interface for json, avro, bson (mongodb). It works perfectly fine. We can use xpath, xslt against json, avro, bson, etc by doing this.

The only thing you have to remember is that some document types are "richer" than others. xml has a value for a node, where most other formats don't.

For example:

<MyDocument>
  <MyChild1>Child1Value</MyChild1>
  <MyChild2>Child2Value</MyChild2>
  <MyChild3 attribute1="Child3 attribute1" attribute2="Child3 attribute2"></MyChild3>
</MyDocument>

To represent the same document in json, you need to introduce a convention. In the below example the convention is to use the key "_rootValue" for node value:

  {
    "MyDocument": {
      "MyChild1": {
        "_rootValue": "Child1Value"
      },
      "MyChild2": {
        "_rootValue": "Child2Value"
      },
      "MyChild3": {
        "attribute1": "Child3 attribute1",
        "attribute2": "Child3 attribute2"
      },
    }
  }
Johan Witters
  • 1,529
  • 11
  • 23