Vani
Vani

Reputation: 1353

XPath to access the label/value nodes in the xml

I am trying to access the label / value nodes in the below xml . I have to match the label and get the Value.

   <OneStopCenterResult>
    <OneStopCenterInfoResults>
    <OneStopCenterInfo>
    <LabelValues>
<Label>Name of Center</Label>
<Value>Arlington Employment Center</Value>
</LabelValues>
<LabelValues>
<Label>ADDRESS_1</Label>
<Value>2100 Washington Blvd</Value>
</LabelValues>
</OneStopCenterInfo>
</OneStopCenterInfoResults>
</OneStopCenterResult>

C#

     XmlDocument xmlDocument =     HelperClass.GetXMLDocument(AJCDetUri);                        
    ltrAJCDetail.Text = GetHTMLTableString(xmlDocument);

C# function call
I am using the below function to retrieve the label/value based on the label value.

 private string GetHTMLTableString(XmlDocument xmlResults)
      {
       //Sort the table based on EmpCount 
        string outPutString = string.Empty;


 XmlNodeList empDetail=null;
            try
            {
//the below code is not working
                 empDetail = xmlResults.SelectNodes("/OneStopCenterResult/OneStopCenterInfoResults/OneStopCenterInfo/LabelValues[Label] ='Name of Center'");

                //foreach (XmlNode node in empDetail)
                //{

                //    Response.Write(" for loop  " + node.SelectSingleNode("/Label").Value);


                //}
            }
            catch (Exception ex)
            {
                Response.Write(" Error  " +ex.ToString()); 
                Response.End();
            }

            }

Thanks in advance

Upvotes: 0

Views: 414

Answers (1)

thrig
thrig

Reputation: 676

You can use XPath directly, though that results in a somewhat complicated expression along the lines of //LabelValues/Value[preceding-sibling::Label[1]="Name of Center"]/text() that looks for the text() of a Value element whose first preceding-sibling::Label element contains Name of Center. Test case via xpquery:

% cat label.xml 
<foo>
<LabelValues>
<Label>Name of Center</Label>
<Value>v</Value>
</LabelValues>
</foo>
% xpquery '//LabelValues/Value[preceding-sibling::Label[1]="Name of Center"]/text()' label.xml
v
% 

Hmm probably implementation dependent; yours gets the element, not the text:

% xpquery '//LabelValues/Value[preceding-sibling::Label="Name of Center"]' label.xml
<Value>v</Value>

Upvotes: 2

Related Questions