Generic XML XPath helper with C# -
problem- have windows application loads xml file , other input takes xpath fetch data user wants given xml (obviously that's not problem). code snippet use load element given xpath like-
xpathdocument docnav; xpathnavigator nav; xpathnodeiterator nodeiter; xmlnamespacemanager manager; docnav = new xpathdocument(filename); nav = docnav.createnavigator(); nav.movetofollowing(xpathnodetype.element); idictionary<string, string> names = nav.getnamespacesinscope(xmlnamespacescope.all); manager = new xmlnamespacemanager(nav.nametable); foreach (keyvaluepair<string, string> item in names) { manager.addnamespace(item.key, item.value); } nodeiter = nav.select(path, manager);
i have 1 sample xml below-
<fpml xmlns:ns="http://www.fpml.org/2005/fpml-4-2"> <header> <messageid>ts4-xyz</messageid> <sentby>xyz</sentby> <creationtimestamp>2017-07-08t08:05:53.929z</creationtimestamp> </header> <trade> <tradeheader> <partytradeidentifier> <partyreference href="our_party"/> <tradeid tradeidscheme="uniqueid">aaaaaa</tradeid> </partytradeidentifier> <partytradeinformation> <partyreference href="our_party"/> <trader>dummy trader name</trader> </partytradeinformation> <tradedate>2017-07-08</tradedate> <tsfpml:completeddatetime>2017-07-08t08:05:53.656z</tsfpml:completeddatetime> </tradeheader> </trade> </fpml>
now, want retrieve 'trader' element value. works if use xpath query
//*[local-name()="trader" , namespace-uri()='http://www.fpml.org/2005/fpml-4-2']
but fails load element if give /fpml/trade/tradeheader/partytradeinformation/trader
what change in xpath helper application required select nodes default namespace in general.
thank in advance!
you can remove namespaces using :
public static string removeallnamespaces(string xmldocument) { xelement xmldocumentwithoutns = removeallnamespaces(xelement.parse(xmldocument)); return xmldocumentwithoutns.tostring(); } private static xelement removeallnamespaces(xelement xmldocument) { if (!xmldocument.haselements) { xelement xelement = new xelement(xmldocument.name.localname); xelement.value = xmldocument.value; foreach (xattribute attribute in xmldocument.attributes()) xelement.add(attribute); return xelement; } return new xelement(xmldocument.name.localname, xmldocument.elements().select(el => removeallnamespaces(el))); }
and called :
var doc = new xmldocument(); doc.load(filename); doc.innertext = removeallnamespaces(doc.innertext); var nav = doc.createnavigator();
Comments
Post a Comment