Skip to main content

Posts

Showing posts with the label select nodes

Cum sa scriem un xPath cand avem definit si un namespace

Cand vrem sa aplicam un xPath pe un xml ce conține si un namespace lucrurile se complica. De exemplu daca pornim de la urmatorul xml: <?xml version="1.0" ?> <x xmlns="http://www.xyz.com/"> <y>1</y> <y>2</y> </x> Daca dorim sa aplicam un xPath am scrie un cod asemanator cu acesta: var xmlDoc = new XmlDocument(); xmlDoc.Load(sursa); var nodes = xmlDoc.SelectNodes(@"/x/y"); Din pacate din cauza ca in xml este definit un namespace, acest lucru nu o sa functioneze. Numarul de noduri returnate va fi mereu 0. Pentru a putea rezvolta aceasta problema trebuie sa adaugam si un namespace, codul rezultat ajungand sa arate in felul urmator: var xmlDoc = new XmlDocument(); xmlDoc.Load(sursa); var nameSpaceManager = new XmlNamespaceManager(xmlDoc.NameTable); nameSpaceManager.AddNamespace("nm","http://www.xyz.com/"); var nodes = xmlDoc.SelectNodes(@"/nm:x/nm:y",nameSpaceManager); Dezavantajul...