2015-09-08 46 views
0

我試圖訪問下面xml中的標籤/值節點。我必須匹配標籤並獲得價值。XPath訪問xml中的標籤/值節點

<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#函數調用
我使用下面的函數來獲取基於標籤值的標籤/值。

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(); 
      } 

      } 

在此先感謝

回答

2

您可以直接使用XPath,雖然在沿//LabelValues/Value[preceding-sibling::Label[1]="Name of Center"]/text(),看起來爲Value元素,其第一preceding-sibling::Label元素包含Name of Centertext()的線條有些複雜表達式的結果。測試案例通過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 
% 

嗯可能實施依賴;你得到的元素,而不是文本:

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

我想你的代碼,但它返回空字符串 – Vani

+0

XmlNode的ajcNode = xmlResults.SelectSingleNode(「/ OneStopCenterResult/OneStopCenterInfoResults/OneStopCenterInfo/LabelValues /標籤[文本()=」中心名稱]]「); - 這返回中心名稱 XmlNode ajcNodeValue = xmlResults.SelectSingleNode(「/ OneStopCenterResult/OneStopCenterInfoResults/OneStopCenterInfo/LabelValues/Value [previous-sibling :: Label [1] ='中心名稱]/text()」);這返回空 – Vani

+0

我剛剛更正了代碼爲XmlNode ajcNodeValue = xmlResults.SelectSingleNode(「/ OneStopCenterResult/OneStopCenterInfoResults/OneStopCenterInfo/LabelValues /值[先前sibling ::標籤='中心的名稱]」);有用 !! – Vani