Accessing a child node by name of an XML document using C# -
i have situation xml document contained similar following, order of "block" elements changed, , in application, accessing value of in using getelementsbytagname("amount")[0].innertext, first occurrence of "amount". order of "blocks" changed, , "amount" returned getelementsbytagname still first occurrence, want "amount" in "block1" returned. how accomplish in c#?
before:
<response xmlns="testsite.com/schema/testservice/2015-01-01"> <block1> <amount>$5.00</amount> </block1> <block2> <amount>$0.00</amount> </block2> <block3> <amount>$0.00</amount> </block3> </response>
after:
<response xmlns="testsite.com/schema/testservice/2015-01-01"> <block2> <amount>$0.00</amount> </block2> <block3> <amount>$0.00</amount> </block3> <block1> <amount>$5.00</amount> </block1> </response>
c#:
xmldocument doc = new xmldocument(); doc.loadxml(response); string amount = doc.getelementsbytagname("amount")[0].innertext;
you can use method selectsinglenode
, xpath expression access data need. need use namespace manager , import correct namespace:
var namespacemanager= new xmlnamespacemanager(doc.nametable); namespacemanager.addnamespace("a", "testsite.com/schema/testservice/2015-01-01"); var xmlnode = doc.selectsinglenode("/a:response/a:block1/a:amount", namespacemanager); var value = node.innertext; // prints $5.00
such code find correct value regardless of block1 - first, second or third element. method selectsinglenode
returns first node matches expression, if have more 1 block1 element in xml results might not expect
Comments
Post a Comment