xml - Java XPath Expression error -
i trying print specific node xml data file such pantone 100 example. print out attributes pantone 100 such colors , data hold unsure of how format xpath compile correctly in way pull specific pantone number i'm looking for.
edit: code below outputs null
xml data
<inventory> <product pantone="100" blue="7.4" red="35" green="24"> </product> <product pantone="101" blue="5.4" red="3" rubine="35" purple="24"> </product> <product pantone="102" orange="5.4" purple="35" white="24"> </product> <product pantone="103" orange="5.4" purple="35" white="24"> </product> <product pantone="104" orange="5.4" purple="35" white="24"> </product> <product pantone="105" orange="5.4" purple="35" white="24"> </product> <product pantone="106" black="5.4" rubine="35" white="24" purple="35" orange="5.4"> </product> </inventory>
code
import org.w3c.dom.*; import javax.xml.xpath.*; import javax.xml.parsers.*; import java.io.ioexception; import org.xml.sax.saxexception; public class xpathdemo { public static void main(string[] args) throws parserconfigurationexception, saxexception, ioexception, xpathexpressionexception { documentbuilderfactory domfactory = documentbuilderfactory.newinstance(); domfactory.setnamespaceaware(true); documentbuilder builder = domfactory.newdocumentbuilder(); document doc = builder.parse("data.xml"); xpath xpath = xpathfactory.newinstance().newxpath(); // xpath query showing nodes value xpathexpression expr = xpath.compile("/inventory/product[@pantone='100']"); object result = expr.evaluate(doc, xpathconstants.nodeset); nodelist nodes = (nodelist) result; (int = 0; < nodes.getlength(); i++) { system.out.println(nodes.item(i).getnodevalue()); } } }
output null
output null because getnodevalue
not applicable here. gettextcontent
give text between start , end tags, e.g. foobar in example:
<product pantone="100" blue="7.4" red="35" green="24">foobar</product>`.
however if want print attribute values resultset:
nodelist nodes = (nodelist)result; (int = 0; < nodes.getlength(); i++) { namednodemap = nodes.item(i).getattributes(); (int j=0; j<a.getlength(); j++) system.out.println(a.item(j)); }
or use a.item(j).getnodename()
or a.item(j).getnodevalue()
retrieve attribute name or value respectively.
Comments
Post a Comment