如何在 JSP 中解析 XML?
jspjava 8object oriented programmingprogramming
<x:parse> 标签用于解析通过属性或在标签主体中指定的 XML 数据。
属性
<x:parse> 标签具有以下属性 −
属性 | 描述 | 必需 | 默认 |
---|---|---|---|
var | 包含已解析 XML 数据的变量 | 否 | 无 |
xml | 要解析的文档文本(字符串或读取器) | 否 | Body |
systemId | 用于解析文档的系统标识符 URI | 否 | 无 |
filter | 要应用于源文档的过滤器 | 否 | 无 |
doc | 要 | 否 | Page |
scope | var 属性中指定的变量的作用域 | 否 | Page |
varDom | 包含已解析 XML 数据的变量 | 否 | Page |
scopeDom | varDom 属性中指定的变量的作用域 | 否 | 页面 |
示例
以下示例展示了如何使用 parse 读取外部 XML 文件 −
我们已经了解了如何从给定文档的正文中解析 XML。现在,我们将以下内容添加到 books.xml 文件中−
<books> <book> <name>Padam History</name> <author>ZARA</author> <price>100</price> </book> <book> <name>Great Mistry</name> <author>NUHA</author> <price>2000</price> </book> </books>
现在尝试以下 main.jsp,保留在同一目录中 −
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix = "x" uri = "http://java.sun.com/jsp/jstl/xml" %> <html> <head> <title>JSTL x:parse Tags</title> </head> <body> <h3>Books Info:</h3> <c:import var = "bookInfo" url = "http://localhost:8080/books.xml"/> <x:parse xml = "${bookInfo}" var = "output"/> <b>The title of the first book is</b>: <x:out select = "$output/books/book[1]/name" /> <br> <b>The price of the second book</b>: <x:out select = "$output/books/book[2]/price" /> </body> </html>
通过http://localhost:8080/main.jsp访问上述JSP,将显示以下结果 −
Books Info: The title of the first book is:Padam History The price of the second book: 2000