从字符串中获取XML属性值
从字符串中获取XML属性值
我正在尝试使用Java Servlet创建一个RESTful webservice。问题是,我必须通过POST方法将请求传递给web服务器。这个请求的内容不是参数,而是请求体本身。
所以,我基本上从Ruby发送了这样的内容:
url = URI.parse(@host) req = Net::HTTP::Post.new('/WebService/WebServiceServlet') req['Content-Type'] = "text/xml" # req.basic_auth 'account', 'password' req.body = data response = Net::HTTP.start(url.host, url.port){ |http| puts http.request(req).body }
然后,我必须在我的servlet中检索这个请求的主体。我使用经典的readline,所以我得到了一个字符串。问题是当我需要将其解析为XML时:
private void useXML( final String soft, final PrintWriter out) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, FileNotFoundException { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); // 不要忘记这一步! DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(soft); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile("//software/text()"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { out.println(nodes.item(i).getNodeValue()); } }
问题是builder.parse()
接受:parse(File f)
、parse(InputSource is)
、parse(InputStream is)
。
有没有办法可以将我的xml字符串转换为InputSource或类似的东西?我知道这可能是一个愚蠢的问题,但Java不是我的专长,我被迫使用它,而且我并不是很熟练。
问题的出现原因是需要从一个字符串中获取XML属性的值。解决方法是通过创建一个InputSource对象,使用StringReader将字符串转换为InputSource,然后使用DOM解析器解析该InputSource对象。
以下是解决该问题的代码示例:
import org.w3c.dom.Document; import org.xml.sax.InputSource; String xmlString = ""; // 创建一个InputSource对象,使用StringReader将字符串转换为InputSource InputSource inputSource = new InputSource(new StringReader(xmlString)); // 使用DOM解析器解析InputSource对象 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(inputSource); // 获取XML属性的值 String attributeValue = doc.getDocumentElement().getElementsByTagName("element").item(0).getAttributes().getNamedItem("attribute").getNodeValue(); content
通过以上代码,我们可以从字符串中获取XML属性的值。首先,我们将字符串包装在StringReader中,然后使用InputSource将StringReader转换为InputSource对象。接下来,我们使用DOM解析器解析InputSource对象,得到一个Document对象。最后,我们可以通过Document对象的方法获取XML属性的值。
以上是解决从字符串中获取XML属性值的方法。通过创建InputSource对象,将字符串转换为InputSource,再使用DOM解析器解析该InputSource对象,我们可以轻松地获取XML属性的值。