从 azure apim 中的 XML 响应中获取属性值

Get an attribute value from XML Response in azure apim

我有 xml 响应存储在响应变量名称中,例如:

<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 然后获得所需的结果。

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

根据命名空间在您的 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
)" />