Wrapping a string in a File object in Jython

324 views Asked by At

I'm trying to do some XML DOM manipulations in an embedded Jython interpreter that doesn't have access to substantial portions of the standard library. To that end, I'm hoping to make use of the java standard library (to which I have access) and utilize org.w3c.dom, the DocumentBuilderFactory, or similar.

The issue is that I have a str holding the XML response and all of these libraries expect a File or InputStream; normally what I'd do in python is wrap the string in a StringIO object, but this doesn't cut it in Java land.

Ideas?

1

There are 1 answers

1
Jeremy Gosling On BEST ANSWER

Slightly off topic as this is a working Jython sample based on the idea in https://stackoverflow.com/a/562207/1774484 which wraps a string as an InputSource rather than a File, but this can then be used with a DocumentBuilderFactory to produce an org.w3c.dom.Document as requested.

import java

from java.io import StringReader
from javax.xml.parsers import DocumentBuilderFactory
from org.xml.sax import InputSource
from javax.xml.xpath import XPathFactory, XPathConstants

myString = "<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE html><html><h1>Hello</h1><h2>world!</h2></html>"

# Create an InputSource from the string
ipsrc = InputSource()
ipsrc.setCharacterStream(StringReader(myString))

# Parse the InputSource creating a Document
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
document = builder.parse(ipsrc)

# Example: Use an XPath statement to extract the contents of all text 
# nodes in the document
xpath = XPathFactory.newInstance().newXPath()
expr = xpath.compile("//*/text()")

nodeset = expr.evaluate(document, XPathConstants.NODESET)

for i in range (0, nodeset.getLength()):
    print nodeset.item(i).getNodeValue()

The above code works in Jython 2.2.1, 2.5.3 and 2.7.0.