0

I have an XML whose data looks like

<Chart>
<History>
<Master_Medication_List>
<Item1>
<ndcnumber>00121478105</ndcnumber>
</Item1>
</Master_Medication_List>
</History>
</Chart>  

Now I want to select node for that using this code

objEncList = objXml.SelectNodes("//Chart/History/Master_Medication_List/Item1/*[ndcnumber='" + strProductCode + "']");  

but it's not selecting any node.

MANISH KUMAR CHOUDHARY
  • 3,326
  • 3
  • 21
  • 32
saudblaze
  • 152
  • 10

3 Answers3

0

It's an element, so you would just access it like:

objEncList = objXml.SelectNodes("//Chart/History/Master_Medication_List/Item1/ndcnumber");

That is the node, the node's value is the actual value.

If you have multiple Item1s, I think you can select it via:

objEncList = objXml.SelectNodes("//Chart/History/Master_Medication_List/Item1/ndcnumber[text()='00121478105']");
Mary Ellen Bench
  • 520
  • 1
  • 7
  • 25
0

You want to select the element by content. ndcnumber[.='content'] is how you do that. So either

objEncList = objXml.SelectNodes("
    //Chart/History/Master_Medication_List/Item1/ndcnumber[.='" + strProductCode + "']"
);

Or, if objXml is the actual root already, omit it:

objEncList = objXml.SelectNodes("
    /History/Master_Medication_List/Item1/ndcnumber[.='" + strProductCode + "']"
);
Jeroen Mostert
  • 25,304
  • 2
  • 44
  • 78
0

If you are looking to select all <Item1> elements with a nested <ndcnumber> element with value 00121478105, you should do:

var itemList = objXml.SelectNodes("//Chart/History/Master_Medication_List/Item1[ndcnumber='" + strProductCode + "']");  

If you are looking to select all <ndcnumber> elements with value 00121478105, you should do:

var ndcnumberList = objXml.SelectNodes("//Chart/History/Master_Medication_List/Item1/ndcnumber[text()='" + strProductCode + "']");  

(It is unclear from your question which you want.)

Notes:

  • XPath queries are case sensitive, so you need to match the element name exactly.
  • You have one too many levels in your query string: Item1/*[ndcnumber=... means "Look for any child of Item1 with a child named ndcnumber with a specific value.
  • If strProductCode is a user-entered string, watch out for XPath injection attacks. See XPath injection mitigation and How to prevent XPath/XML injection in .NET.

Example fiddle.

dbc
  • 91,441
  • 18
  • 186
  • 284