我正在尝试在嵌入式 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/