java - How to parse XML file to retrieve certain values -
i have xml file bunch of data
example:
<?xml version="1.0" encoding="utf-8" standalone="no"?> <nodes topic="filingstatus"> <versions> <version id="tke.calc.fileformat">4</version> <version id="tke.calc.runtime">1</version> <version id="tke.gist">12</version> <version id="tke.mef">1</version> </versions> <!-- common --> <node name="/temporary/filingstatus/singlemaritalstatus"> <inputs> <input>/return/returndata/ppreturninformation/maritalstatuspp</input> <input>/constants/irs1040/filingstatus/singlemaritalstatus</input> </inputs> <gist> <equals> <inputroles> <value>/return/returndata/ppreturninformation/maritalstatuspp</value> <value>/constants/irs1040/filingstatus/singlemaritalstatus</value> </inputroles> </equals> </gist> </node> <node name="/temporary/filingstatus/divorcedmaritalstatus"> <inputs> <input>/return/returndata/ppreturninformation/maritalstatuspp</input> <input>/constants/irs1040/filingstatus/divorcedmaritalstatus</input> </inputs> <gist> <equals> <inputroles> <value>/return/returndata/ppreturninformation/maritalstatuspp</value> <value>/constants/irs1040/filingstatus/divorcedmaritalstatus</value> </inputroles> </equals> </gist> </node> </nodes> i'd way in java parse file , retrieve me data node attribute "name" (like here node name="some text value") , tag value below "gist" tag name here:
<gist> <equals> <--------i want value here ... </equals> </gist> example: example xml posted above, i'd retrieve follow data:
[/temporary/filingstatus/singlemaritalstatus, equals] [/temporary/filingstatus/divorcedmaritalstatus, equals]
so i'd data returned me paired in linked hash map (so order kept in tact).
i prefer avoid dom or stax parsing, think there should nice way of doing via regex. or advisement appreciated.
when want search in xml document, want use xpath expressions:
static map<string, node> parseequalsbyname(string filename) throws ioexception, xpathexception { xpath xpath = xpathfactory.newinstance().newxpath(); map<string, node> equalsbyname = new linkedhashmap<>(); try (inputstream file = new bufferedinputstream( files.newinputstream(paths.get(filename)))) { nodelist nodes = (nodelist) xpath.evaluate("//node", new inputsource(file), xpathconstants.nodeset); int nodecount = nodes.getlength(); (int = 0; < nodecount; i++) { node node = nodes.item(i); string name = node.getattributes().getnameditem("name").getnodevalue(); node equals = (node) xpath.evaluate("gist/equals", node, xpathconstants.node); equalsbyname.put(name, equals); } } return equalsbyname; } regular expressions bad idea evaluating xml. it's unlikely can handle things comments, cdata sections , character entities.
Comments
Post a Comment