gpt4 book ai didi

c# - 使用 LINQ 搜索、添加和更新

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:39 25 4
gpt4 key购买 nike

我需要能够按 ServerGroup 跟踪工作项。每个 ServerGroup 可能有多个 FaultCode。

我应该使用什么是最好的 XML 布局? 选项 A 或 B? 我能够创建一个 linq 查询来搜索选项 A。但我不确定如何检查故障代码。因此,我想到了选项 B,因为它允许我将 ServerGroup 和 FaultCode 分组。当 xml 的结构类似于选项 B 时,是否可以执行 linq 搜索?

感谢您的帮助。

<?xml version="1.0" encoding="utf-16"?>
<CapacityIssues xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

**//Option A**
<TrackingDetails>
<ServerGroup>A</ServerGroup>
<FaultCode>123</FaultCode>
<ID>4123567</ID>
<Title>Capacity Issues</Title>
<AssignedTo>Team A</AssignedTo>
<Description>Server Group A has an issue</Description>
<State>Active</State>
<Priority>2</Priority>
</TrackingDetails>

**//Option B**
<TrackingDetails ServerGroup="A" FaultCode="123">
<ID>4123567</ID>
<Title>Capacity Issues</Title>
<AssignedTo>TeamA</AssignedTo>
<Description>This is a test</Description>
<State>Active</State>
<Priority>0</Priority>
</TrackingDetails>

</CapacityIssues>

我能够使用选项 A 进行搜索,这是我编写的代码。

public static Dictionary> TFS(字符串文件路径) { //设置要读取的文档类型 XDocument doc = XDocument.Load(文件路径);

    //execute reading of xml document
if (doc == null || doc.Root == null)
{
throw new ArgumentException($"Null document loaded from {filePath}");
}

return doc.Root.Elements("TfsDetails").ToDictionary(r =>
r.Element("ServerGroup").Value,
r => Tuple.Create(
r.Element("FaultCode").Value,
r.Element("ID").Value,
r.Element("Title").Value,
r.Element("AssignedTo").Value,
r.Element("Description").Value,
r.Element("State").Value,
r.Element("Priority").Value
));
}

这是我将选项 B 元素添加到 XML 文件的方式

private static void Create(string filePath)
{
//load xml file
XDocument doc = XDocument.Load(filePath);

//xmnl header
XElement root = new XElement("CapacityIssues");

//node root
root.Add(new XAttribute("ServerGroup", "A"));

//cluster and TFS details
root.Add(new XAttribute("FaultCode", "111"));
root.Add(new XElement("ID", "4123567"));
root.Add(new XElement("Title", "Capacity Issues"));
root.Add(new XElement("AssignedTo", "Team A"));
root.Add(new XElement("Description", "ServerGroup A has an issue"));
root.Add(new XElement("State", "Active"));
root.Add(new XElement("Priority", "0"));

//add new element
doc.Element("CapacityIssues").Add(root);

//save xml file
doc.Save(filePath);
}

最佳答案

当然,虽然两者都有效,但建议是选项 B(使用属性而不是元素),因为它的深度较小。

您可以对 Attributes 使用 linq,如下所示。

foreach (var xAttribute in root.Descendants("TrackingDetails").Attributes().Where(o => o.Name.Equals("ServerGroup")))
{
// do something about ServerGroup A or B
}

关于c# - 使用 LINQ 搜索、添加和更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36684398/

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