none
XML parsing help RRS feed

  • Question

  • Hi,

    I need to grab the "Quantity" value from the below xml code using C#:

    <td>
    <content styleCode="xContentWrapping">
    <content ID="_42da39b0-83d2-4906-b8d9-531456d3220b">ALPRAZolam 0.25 MG Oral Tablet</content>
    <content styleCode="xLabel">; </content>
    <content styleCode="xSecondary" ID="_5eba331f-cc26-4e5b-a9fb-fb2614bc14a4">two times daily [2]</content>
    <br />
    <content styleCode="xLabel"> Quantity: </content>
             <content>180 </content>
    <br />
    <content styleCode="xLabel xSecondary">Refills: </content>
    <content styleCode="xSecondary">3</content>
    <br />
    </content>
    </td>

    Is there a simple way to do this or do I need to interrogate each tag to get this?

    Friday, May 10, 2019 8:58 PM

All replies

  • If this text is loaded into an XmlDocument (using Load or LoadXml), then check this:

    XmlDocument doc = . . .
    XmlNode n = doc.SelectSingleNode( "//content[@styleCode='xLabel' and normalize-space(.)='Quantity:']/following-sibling::content" );
    string value = n.InnerText.Trim( );



    • Edited by Viorel_MVP Saturday, May 11, 2019 7:50 AM
    Saturday, May 11, 2019 7:49 AM
  • Would this work if I used XmlData instaed of XmlDoc? The code has is using XmlData in C#.
    Monday, May 13, 2019 3:55 PM
  • Hi robert049,

    To complement Viorel's solution, here is a full example for you by using Linq to XML:

    void Main()
    {
    	XElement xml = XElement.Parse(@"<td>
    		<content styleCode='xContentWrapping'>
    			<content ID='_42da39b0-83d2-4906-b8d9-531456d3220b'>ALPRAZolam 0.25 MG Oral Tablet</content>
    			<content styleCode='xLabel'>;</content>
    			<content styleCode='xSecondary' ID='_5eba331f-cc26-4e5b-a9fb-fb2614bc14a4'>two times daily [2]</content>
    			<br/>
    			<content styleCode='xLabel'>Quantity:</content>
    			<content>180</content>
    			<br/>
    			<content styleCode='xLabel xSecondary'>Refills:</content>
    			<content styleCode='xSecondary'>3</content>
    			<br/>
    		</content>
    	</td>");
    	
    string quantity = xml.Descendants("content")
    			.FirstOrDefault(x => (string)x.Attribute("styleCode") == "xLabel" && x.Value == "Quantity:")
    			.ElementsAfterSelf().FirstOrDefault().Value;
    }
    Monday, May 13, 2019 5:10 PM