Re: Don't understand NodeModel.get with XML
Stephan Müller <[email protected]>
| Newsgroups | gmane.comp.web.freemarker.user |
|---|---|
| Message-ID | <[email protected]> |
Ista Pouss schrieb:
> Hi,
>
> If I do that :
>
> String txt = "<root><a/><b/></root>";
> NodeModel mod = NodeModel.parse(
> new InputSource(new StringReader(txt)));
> System.out.println("hope it's root ? = "+mod);
> System.out.println("hope it's a ? = "+mod.get(0));
> System.out.print("hope it's b ? = "+mod.get(1));
>
>
> I see on console :
>
> hope it's root ? = freemarker.ext.dom.DocumentModel@108786b
> hope it's a ? = freemarker.ext.dom.DocumentModel@108786b
> hope it's b ? = null
>
First of all, I don't see why you try to navigate through the wrapped
DOM document like this, since the main (and only) intended use of the
NodeModel API is from inside a FreeMarker template. Nevertheless it is
possible to achieve this with the NodeModel API. One problem is that the
result of NodeModel.parse() returns the document node, not the
document's root node. Secondly, AFAIK, you cannot use the
NodeModel.get(int) methods to access the child nodes. You have to use
NodeModel.getChildNode().get(int) instead:
String txt = "<root><a/><b/></root>";
NodeModel documentNode = NodeModel.parse(
new InputSource(new StringReader(txt)));
NodeModel rootNode = (NodeModel)documentNode.getChildNodes().get(0);
System.out.println("hope it's root ? = "+rootNode.getNodeName());
NodeModel nodeA = (NodeModel)rootNode.getChildNodes().get(0);
System.out.println("hope it's a ? = "+nodeA.getNodeName());
NodeModel nodeB = (NodeModel)rootNode.getChildNodes().get(1);
System.out.print("hope it's b ? = "+nodeB.getNodeName());
Alternatively you can use XPath expressions to navigate through the
document:
ArrayList xpath = new ArrayList();
xpath.add("/root/a");
NodeModel anotherNodeA = (NodeModel)documentNode.exec(xpath);
System.out.println("hope it's a ? = "+anotherNodeA.getNodeName());
HTH,
Stephan.
-------------------------------------------------------------------------
This SF.net email is sponsored by the 2008 JavaOne(SM) Conference
Don't miss this year's exciting event. There's still time to save $100.
Use priority code J8TL2D2.
http://ad.doubleclick.net/clk;198757673;13503038;p?http://java.sun.com/javaone