c# - 如何从 Xml 文件中获取逗号分隔值

标签 c# xml

我的 xml 文件看起来像这样(我在这个 xml 上有很多数据,但这是相关的行)

<add Key="CpaData" Value="62502634,10:64917154,15:205481314,20:205485754,25"/>

我需要从 CpaData key value 获取值,我有一些元素(数组,列表),其中我有用“:”分隔的元素,就像这样 62502634,10 ,在它之后我需要访问一个此次出售(62502634 或 10) 我的代码看起来像这样

private int GetTargetCpaData(string campaignId)
{
    var path = HttpContext.Current.Server.MapPath(@"reportConfig1.xml");
    XDocument doc = XDocument.Load(path);
    int i = 0;
    var elements = doc.Descendants("Configuration");
    string cpaValues = "";
    var cpaDataValues = doc.Descendants().Attributes().FirstOrDefault(node => node.Value == "CpaData").ToString();
    string[] temp = cpaDataValues.Split(new string[] { ":" }, StringSplitOptions.None);
    foreach (string items in temp)
    {
        string[] temp2 = items.Split(new string[] { "," }, StringSplitOptions.None);
        if (temp2[i] == campaignId)
        {
            cpaValues = temp2[i + 1];
        }
    }
    return Int32.Parse(cpaValues);
}

但出于某种原因,“cpaDataValues”返回:“add Key="CpaData"而不是值字符串。 我做错了什么?

最佳答案

您需要过滤一个属性,然后返回一个不同的属性,如下所示:

    var cpaDataValues = doc.Descendants()                   // Search all elements of the document
        .Where(e => e.Name.LocalName == "add")              // Look for element with local name "add"
        .Where(e => (string)e.Attribute("Key") == "CpaData")// With an attribute named "Key" with value "CpaData"
        .Select(e => (string)e.Attribute("Value"))          // Select the value of the "Value" attribute.
        .FirstOrDefault();                                  // And return the first found.

我搜索的是元素本地名称而不是名称,因为您的问题中可能没有显示默认 namespace 。

关于c# - 如何从 Xml 文件中获取逗号分隔值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30910178/

相关文章:

c# - 使用 C# 控制另一个应用程序

sql-server - 如何使用带有多个子节点的sql将表数据转换为xml格式

java - 添加了新的bean.xml并获取类路径资源[Spring-Mail.xml]无法打开,因为它不存在],其根本原因

xml - 如何在 Xpath "contains()"函数中使用变量节点集

java - Unmarshalexception 意外元素,预期元素是(无)

c# - 在 WebBrowser 控件中将字符串数组从 JS 传递到 C#

C# 如何在没有 bool 的情况下执行 Try Catch Finally 来释放资源?

c# - ASP.Net双击问题

c# - 将窗口按钮置于前面

android - 我怎样才能使 RelativeLayout 适合屏幕?