Dúvida sobre xpath

3 respostas
Ed.prog

Estou tentando pela jstl xml do jsp selecionar um elemento filho, dentro de um elemento pai que tenha determinado nome. Tentei usar esse select: $file/root/father[@name=‘children’][1]/child[1] mas nada aparece… no entanto, $file/root/father[@name=‘children’][1] exibe os elementos dentro de father. O xml seria algo assim:

<root>
    <father name="children">
        <child id="juca">Juca Teste</child>
    </father>
</root>

O que está errado?

3 Respostas

rogeriopaguilar

Eu não testei no jsp, mas no código java funciona:

package teste;

import java.io.ByteArrayInputStream;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.xml.sax.InputSource;

public class XPathEvaluator {

	public void evaluateDocument() {

		try {
			XPathFactory factory = XPathFactory.newInstance();
			XPath xPath = factory.newXPath();
			byte b[] = ("<root> " + " <father name=\"children\"> "
					+ "    <child id=\"juca\">Juca Teste</child> "
					+ " </father> " + " </root> ").getBytes();

			InputSource inputSource = new InputSource(new ByteArrayInputStream(
					b));
			XPathExpression xPathExpression = xPath
					.compile("root/father[@name='children'][1]/child[1]");
			String title = xPathExpression.evaluate(inputSource);
			System.out.println(title);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] argv) {

		XPathEvaluator evaluator = new XPathEvaluator();
		evaluator.evaluateDocument();

	}

}
rogeriopaguilar

Agora eu fiz no jsp e também funcionou:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>
<html>

  <body>XML:
  <br />

  <form method="post">
    <textarea rows="10" cols="50" name="xml">
<root>
    <father name="children">
        <child id="juca">Juca Teste</child>
    </father>
</root>
	</textarea>
    <br />

    <input type="submit" />
  </form>

  <c:if test="${pageContext.request.method=='POST'}">

    <x:parse var="file" xml="${param.xml}"  />

    <table border="1">
      <tr>
        <td>$file/root/father[@name='children'][1]/child[1]</td>

        <td>
          <x:out select="$file/root/father[@name='children'][1]/child[1]" />
        </td>
      </tr>

    </table>
  </c:if>
  </body>
</html>
Ed.prog

Hmm… realmente, testei com o seu código e funcionou, rsrs… o erro foi mais de bobeira mesmo, pois o código de gerava a tag father aqui, estava escapando os caracteres… valeu pelo teste!

Criado 26 de outubro de 2011
Ultima resposta 26 de out. de 2011
Respostas 3
Participantes 2