java - 在 Jython 中将字符串包装在 File 对象中

标签 java jython

我正在尝试在嵌入式 Jython 解释器中执行一些 XML DOM 操作,该解释器无法访问标准库的大部分内容。为此,我希望利用 java 标准库(我可以访问)并利用 org.w3c.dom、DocumentBuilderFactory 或类似的库。

问题是我有一个 str 保存 XML 响应,并且所有这些库都需要 File 或 InputStream;通常我在 python 中所做的是将字符串包装在 StringIO 对象中,但这并不能在 Java 领域中实现。

想法?

最佳答案

有点偏离主题,因为这是一个基于 https://stackoverflow.com/a/562207/1774484 中的想法的工作 Jython 示例它将字符串包装为 InputSource 而不是 File,但随后可以将其与 DocumentBuilderFactory 一起使用以根据请求生成 org.w3c.dom.Document。

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()

以上代码适用于 Jython 2.2.1、2.5.3 和 2.7.0。

关于java - 在 Jython 中将字符串包装在 File 对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30809347/

相关文章:

python - 如何知道代码中的解释器是 Jython 还是 CPython?

java - 从 Java 的 ADFS SAML .NET 服务器获取请求 token

java - Websocket 阻塞,不会因客户端拔出/断电而超时

java - 数组内的数组未按预期工作

jython - 如何使用 Jython 设置 WebSphere 7 中的 'Prefix new alias names with the node name of the cell'?

python - 从另一个 sikuli 项目运行 Sikuli 文件

java - 在 MATLAB 外部运行 MATLAB 函数时 MatlabControl 中出现异常

java - 为什么 Log4j2 不允许多次重新配置包记录器

java - 将 unicode 字符传递给 Jython

python - Jython 与 CPython - sys 模块参数解析