【问题标题】:How to extract value from this XML in JSP如何在 JSP 中从此 XML 中提取值
【发布时间】:2013-04-08 16:53:57
【问题描述】:

我有一个如下的 XML(有 100 行):

    <root>

      <data v="1.0">

        <cellimage counter="0" cash_filename="C:\Temp\_TempFolder\39d437f08cc302876a70a0f91b137991_h.jpg" width="94" height="141" />

        <cellimage counter="1" cash_filename="C:\Temp\_TempFolder\39d437f08cc302876a70a0f91b137991_h.jpg" width="94" height="141" />

      </data>

    </root>

谁能告诉我如何循环遍历它并从 JSP 中的上述 XML 文件中提取“counter”和“cash_filename”等属性。

到目前为止,我有以下代码:

    <%
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse("http://localhost:8080/data.xml");

        NodeList nl = doc.getElementsByTagName("cellimage");
            for (int i = 0; i < nl.getLength(); i++) {
                //Not sure what to do here!
            }
    %>

【问题讨论】:

  • 你尝试过什么?任何关于 DOM 与 Java 的基本教程都应该为您提供指导。
  • 我尝试了来自easywayserver.com/blog/java-read-xml-file 的教程,但是因为该教程正在使用我需要使用属性的子元素,所以教程中的代码对我不起作用,并且由于空指针而引发错误。

标签: java xml jsp xml-parsing


【解决方案1】:

你可以很简单地得到你的物品:

NodeList nl = doc.getElementsByTagName("cellimage");
    Element el;
    Integer counter;
    String fName;

    for (int i = 0; i < nl.getLength(); i++) {
        //Not sure what to do here!
        el = (org.w3c.dom.Element) nl.item(i);
        counter = Integer.valueOf(el.getAttribute("counter"));
        fName = el.getAttribute("cash_filename");
    }

【讨论】:

    猜你喜欢
    • 2017-08-11
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多