在 Jython 中将字符串包装在 File 对象中
Wrapping a string in a File object in Jython
我正在尝试在无法访问标准库的大部分内容的嵌入式 Jython 解释器中进行一些 XML DOM 操作。为此,我希望利用 java 标准库(我可以访问它)并利用 org.w3c.dom
、DocumentBuilderFactory
或类似库。
问题是我有一个 str
持有 XML 响应,所有这些库都需要一个 File 或 InputStream;通常我在 python 中所做的是将字符串包装在 StringIO
对象中,但这并没有在 Java 领域中削减它。
想法?
稍微偏离主题,因为这是一个基于 中想法的工作 Jython 示例,它将字符串包装为 InputSource 而不是文件,但这可以与 DocumentBuilderFactory 一起使用以生成组织.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。
我正在尝试在无法访问标准库的大部分内容的嵌入式 Jython 解释器中进行一些 XML DOM 操作。为此,我希望利用 java 标准库(我可以访问它)并利用 org.w3c.dom
、DocumentBuilderFactory
或类似库。
问题是我有一个 str
持有 XML 响应,所有这些库都需要一个 File 或 InputStream;通常我在 python 中所做的是将字符串包装在 StringIO
对象中,但这并没有在 Java 领域中削减它。
想法?
稍微偏离主题,因为这是一个基于 中想法的工作 Jython 示例,它将字符串包装为 InputSource 而不是文件,但这可以与 DocumentBuilderFactory 一起使用以生成组织.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。