【问题标题】:Get an attribute value from XML Response in azure apim从 azure apim 中的 XML 响应获取属性值
【发布时间】:2021-08-02 08:12:08
【问题描述】:

我将 xml 响应存储在 response-variable-name 中,例如:

<VS>
<V>
<B n="1" v="X"/>
<B n="2" v="Y"/>
<B n="3" v="Z"/>
<B n="4" v="XX"/>
<B n="5" v="YY"/>
<B n="6" v="ZZ"/>
</V>
</VS>

我想解析这个 xml 响应并使用 apim 策略获取 v 的值,其中 n=3。 约束是我无法将此响应转换为 JSON 并获得所需的结果。

【问题讨论】:

    标签: c# xml azure azure-api-management


    【解决方案1】:

    根据您的 XML 代码中命名空间的确切组织方式,可能会稍微简化一下,但它应该也可以正常工作:

    <set-variable name="test" value="@(
        context.Request.Body.As<XElement>()
            .Descendants()
            .FirstOrDefault(x => x.Name.LocalName == "B" && x.Attributes().FirstOrDefault(a => a.Name.LocalName == "n")?.Value == "3")?
            .Attributes()
            .FirstOrDefault(a => a.Name.LocalName == "v")?
            .Value
    )" />
    

    【讨论】:

      【解决方案2】:

      将 Xml Linq 与字典一起使用:

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Xml;
      using System.Xml.Linq;
      
      namespace ConsoleApplication195
      {
          class Program
          {
              const string FILENAME = @"c:\temp\test.xml";
              static void Main(string[] args)
              {
                  XDocument doc = XDocument.Load(FILENAME);
      
                  Dictionary<int, string> dict = doc.Descendants("B")
                      .GroupBy(x => (int)x.Attribute("n"), y => (string)y.Attribute("v"))
                      .ToDictionary(x => x.Key, y => y.FirstOrDefault());
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2016-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-03
        • 1970-01-01
        • 1970-01-01
        • 2021-11-17
        相关资源
        最近更新 更多