c# - 如何从 C# 中的 ApplicationParameters 文件中获取参数值
问题描述
我有 Azure Service Fabric 项目,它包含用于配置文件的 ApplicationParameters 文件夹。请检查下面的图片。
我想从我的 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 项目的情况下,如何阅读它?
解决方案
我不得不采取两种方式。目前我所知道的参数中没有原生的读取方式。
使用方法从解析的 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);
推荐阅读
- javascript - 如何从文件夹加载 html 文件并将它们显示为本地网页上的链接(用新问题编辑)
- sql - 库存需要查询
- python - 将行值解析为列并用于查找值
- python-3.x - 如何使用 matplotlib 编写绘图标题和轴标题?
- android - 如何在 Android 中获取仪器测试的代码覆盖率
- javascript - 纹理未加载到对象上
- python-3.x - 编写一个函数,从字符串中删除所有出现的给定字母
- google-cloud-platform - 当应用程序请求登录时,Google Oauth 提供了额外的范围
- c - 在命令行中声明 -n 参数以接受整数 - C
- c# - Swagger UI 未在 azure .net 核心中生成,但在本地工作