首页 > 解决方案 > 如何从 C# 中的 ApplicationParameters 文件中获取参数值

问题描述

我有 Azure Service Fabric 项目,它包含用于配置文件的 ApplicationParameters 文件夹。请检查下面的图片。

xml文件

我想从我的 C# 代码中的“Local.1Node.xml”文件中读取“EndPoint”参数的值。

Local.1Node.xml:

<?xml version="1.0" encoding="utf-8"?>
<Application xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="fabric:/Pharmerica.EMessaging.Inbound.Processor.Asf" xmlns="http://schemas.microsoft.com/2011/01/fabric">
  <Parameters>
    <Parameter Name="EndPoint" Value="www.abc.com/api/get" />
  </Parameters>
</Application>

C#:

从 app.config 文件中,我们可以读取如下。

var endPoint = ConfigurationManager.AppSettings["EndPoint"];

在 Azure Service Fabric 项目的情况下,如何阅读它?

标签: c#xml.net-coreazure-service-fabric

解决方案


我不得不采取两种方式。目前我所知道的参数中没有原生的读取方式。

  • 使用方法从解析的 XML 中查找值。

  • 在解析和获取值之前使用 REGEX修复 XML

功能

您可以使用适用于每个 xml 文件的方法从 XML 文件中检索值。提供一些基本的东西,你应该得到值(如果它存在,否则为 null)。以下是从上到下的递归方法。

    public static string GetValueForAttribute(XmlNode element, string elementName, string attribute)
    {
        string value = string.Empty;
        if (element.HasChildNodes)
        {
            foreach (XmlNode node in element.ChildNodes)
            {
                value = GetValueForAttribute(node, elementName, attribute);
                if (!string.IsNullOrEmpty(value))
                    return value;
            }
        }
        else
        {
            if (element.Name.Equals(elementName) && element.Attributes["Name"].Value.Equals(attribute))
                return element.Attributes["Value"].Value.ToString();
        }
        return value;
    }

上述方法的用法是...

    XmlDocument doc = new XmlDocument();
    doc.Load(Path + XMLFileName);

    string value = GetValueForAttribute(doc.DocumentElement, "Parameter", "EndPoint");

正则表达式

另一种读取 XML 的方法是删除元素中的名称空间。以下方法来自该站点。

    string filter = @"xmlns(:\w+)?=""([^""]+)""|xsi(:\w+)?=""([^""]+)""";
    string fileContent = File.ReadAllLines(path + XMLFileName);
    string filteredFile = Regex.Replace(fileContent, filter, "");

    XmlDocument doc2 = new XmlDocument();
    doc2.Load(Path + XMLFileName);

    string value = doc2.SelectNodes("//Application/Parameters/Parameter")
                       .Cast<XmlNode>() // Converts the Collection to List
                       .Where(x => x.Attributes["Name"].Value.Equals("EndPoint"))
                       .Select(x => x.Attributes["Value"].Value.ToString())
                       .FirstOrDefault(); // First would be value .. default would be null.

    if (!string.IsNullOrEmpty(value))
        Console.WriteLine(value);

推荐阅读