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,396
  • 3
  • 22
  • 34
saudblaze
  • 150
  • 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
  • 589
  • 1
  • 8
  • 28
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
  • 27,176
  • 2
  • 52
  • 85
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
  • 104,963
  • 20
  • 228
  • 340