gpt4 book ai didi

C# 使用 linq 查找匹配两个元素级别的 xml 元素

转载 作者:数据小太阳 更新时间:2023-10-29 02:33:52 26 4
gpt4 key购买 nike

我正在尝试从 xml 文档中选择一个 XElement 并匹配 xml 文档的两个“级别”。我的文件结构是:

<app>
<Library Name="Main" Path="C:\somefile.Xml">
<ReadingList Name="Test1">
<Book>...
<ReadingList Name="Test2">
<Book>...
<Library Name="Backup" Path="C:\somefile.Xml">

我想在图书馆“Main”中找到名为“test2”的阅读列表,这样我就可以将这个元素和所有子元素复制到另一个图书馆节点。

我更喜欢使用 linq 的解决方案,因为我正在尝试学习它。

在此先感谢您的帮助

当我添加一个新的“阅读列表”时,我是这样做的:

public void AddReadingList(string fullyQualifiedPath, Library lib, string name)
{
XDocument xdoc = XDocument.Load(fullyQualifiedPath);

XElement library = xdoc.Element("eStack").Elements("Library")
.Single(x => x.Attribute("Name").Value == lib.Name);

library.Add(new XElement("ReadingList", new XAttribute("Name", name)));

xdoc.Save(fullyQualifiedPath);
}

但是我要执行的操作是复制这个元素和子元素。问题是,可能有多个同名的“图书馆”元素,所以我需要检查图书馆名称和阅读列表名称。那有意义吗?

最佳答案

结合使用 .DescendantsWhere 可以解决问题:

var result = XDocument.Load(fullyQualifiedPath)
.Descendants("Library")
//Can replace with `FirstOrDefault` if you know there is only one
.Where(element => element.Attribute("Name")?.Value == "Main")
.Descendants("ReadingList")
.Where(element => element.Attribute("Name")?.Value == "Test2").ToList();

您也可以使用 .Elements 而不是 Descendants 我只是更喜欢使用它,所以不指定 app 的级别或任何其他沿途。


对于之前的 c# 6.0,你可以这样做:

var result = XDocument.Load("data.xml")
.Descendants("Library")
.Where(element =>
{
var att = element.Attribute("Name");
return att != null ? (att.Value == "Main" ? true : false) : false;
})
.Descendants("ReadingList")
//Make sure to do above change here too
.Where(element => element.Attribute("Name")?.Value == "Test2").ToList();

或者如果创建一个方法来帮助它而不是重复代码:

 Func<XElement, string, string> tryGetAttributeValue = (element, attributeName) =>
{
var attribute = element.Attribute(attributeName);
return attribute == null ? string.Empty : attribute.Value;
};

var result = XDocument.Load("data.xml")
.Descendants("Library")
.Where(element => tryGetAttributeValue(element,"Name") == "Main")
.Descendants("ReadingList")
.Where(element => tryGetAttributeValue(element, "Name") == "Test2").ToList();

关于C# 使用 linq 查找匹配两个元素级别的 xml 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39855965/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com