通过指定另一个来拉取一个值

时间:2015-06-10 20:25:17

标签: xml xpath

对于以下XML代码段 -

 String line = "xxx/qwerty/asdfg/xxx/zxcvb";
 string[] words = line.Split('/');
  for (int i = 0; i < words.Length; i++)
   {
       if (words[i].Contains("xxx"))
        {
                Console.WriteLine(words[i]); //current word
                if (i == 0)
                    Console.WriteLine("No Previous Word");
                else
                    Console.WriteLine(words[i - 1]); //PreviousWord

                if (i == words.Length - 1)
                    Console.WriteLine("No Next Word");
                else                                           
                    Console.WriteLine(words[i + 1]); //NextWord
         }
    }

我想通过指定campaign_name文本来获取campaign_key文本。我知道如何通过指定广告系列号来返回campaign_key文本(在这种情况下,&#34; 1&#34;)但我需要能够将campaign_name作为参数传递(在这种情况下,&#34;测试对于邮件列表&#34;)并返回密钥(在这种情况下,&#34; somekeyvalue&#34;)。

2 个答案:

答案 0 :(得分:1)

要根据名称检索广告系列密钥,请使用

/response/recent-sent-campaigns/campaign[fl[@val = 'campaign_name'] = 'Test for Mailing List']/fl[@val = 'campaign_key']

表示

/response                   select the `response` element
/recent-sent-campaigns      select its children `recent-sent-campaigns`
/campaign                   select its children `campagin`
[fl[@val = 'campaign_name'] but only if there is a child element called `fl` which has an
                            attribute called `val` whose value is "campaign_name"
= 'Test for Mailing List']  and only if the text content of that `fl` element is "Test for
                            Mailing List"
/fl[@val = 'campaign_key']  of any elements satisfying this condition, select their
                            children `fl` where there is an attribute `val` whose value is
                            equal to "campaign_key"

并因此产生结果:

<fl val="campaign_key">somekeyvalue</fl>

如果您只想返回此元素的文本内容,请在结尾添加/text()

/response/recent-sent-campaigns/campaign[fl[@val = 'campaign_name'] = 'Test for Mailing List']/fl[@val = 'campaign_key']/text()

,结果将是

somekeyvalue

答案 1 :(得分:0)

我不会依赖于xml结构的确切知识。我们可以在相同的父级

下找到相关的fl并取fl campaign_key
//fl[@val="campaign_name" and .="Test for Mailing List"]/../fl[@val="campaign_key"]/text()