我一直在努力找出如何从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
}
}
您可以通过两种不同的方式选择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();
....
}
我希望这对您有所帮助。
尝试以下操作:
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:temptest.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; }
}
}