【问题标题】:C# and LINQ.XML Select from XMLC# 和 LINQ.XML 从 XML 中选择
【发布时间】:2020-05-22 10:36:29
【问题描述】:

我一直在努力找出如何从 XML 文件中选择多个值,将它们与一个特殊值进行比较,然后做一些事情。到目前为止,我只是设法选择了一个值,但我还需要在同一个选择中使用不同的值,希望您能帮助我

XML 结构

<?xml version="1.0" encoding="utf-8"?>
<userConnectionSettings version="1" lastApplicationUrl="xxx" lastIdentity="yyy">
    <application url="xxx" lastFolderId="zzz">
        <user name="test" domain="domain.tld" lastFolderId="yyy" />
    </application>
</userConnectionSettings>

现在基本上,我要做的是读取lastApplicationURL 和域值。我设法做到了lastApplicationURL,但我似乎无法选择域,而且我不知道如何正确获取该值。这是我的代码:

XDocument foDoc = XDocument.Load(FrontOfficePath);

foreach (var FOurl in foDoc.Descendants("userConnectionSettings"))
{
    string FOappURL = (string)FOurl.Attribute("lastApplicationUrl");

    if (FOappURL == "something")
    {
        TODO
    }
    else
    {
         TODO
    }
}

【问题讨论】:

  • 你试过FOurl.Element("application").Element("user").Attribute("domain")吗?
  • 成功了,谢谢!

标签: c# xml linq


【解决方案1】:

您可以通过两种不同的方式选择domain 属性:
1 - 喜欢@Juharr 评论:

foreach (var FOurl in foDoc.Descendants("userConnectionSettings"))
{
    string domain = FOurl
        .Element("application")
        .Element("user")
        .Attribute("domain")
        .Value;
....
}

或者,通过获取application 的后代并选择第一项,例如:

foreach (var FOurl in foDoc.Descendants("userConnectionSettings"))
{
    string domain = FOurl.Descendants("application")
        .Select(x => x.Element("user").Attribute("domain").Value)
        .FirstOrDefault();
....
}

希望对您有所帮助。

【讨论】:

  • 啊,我明白了,完美,非常感谢您的澄清。我不知道您必须像这样选择它(通过属性)。完美工作:)!
【解决方案2】:

尝试以下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            List<Application> applications = doc.Descendants("application").Select(x => new Application()
            {
                url = (string)x.Attribute("url"),
                id = (string)x.Attribute("lastFolderId"),
                name = (string)x.Element("user").Attribute("name"),
                domain = (string)x.Element("user").Attribute("domain"),
                folder = (string)x.Element("user").Attribute("lastFolderId")
            }).ToList();
        }
    }
    public class Application
    {
        public string url { get; set; }
        public string id { get; set; }
        public string name { get; set; }
        public string domain { get; set; }
        public string folder { get; set; }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多