gpt4 book ai didi

c# - 我可以更好地重写这个 LINQ to XML 吗?

转载 作者:行者123 更新时间:2023-11-30 21:22:16 24 4
gpt4 key购买 nike

我刚刚开始学习 LINQ,尤其是 LINQ to XML,我已经编写了一个有效的查询,但我想知道我是否正在做一些循环。代码可以改进吗?

我有一个 XDocument:

<SomeDocument>
<Prop1> val1 </Prop1>
<Prop2> val2 </Prop2>
<Prop3> val3 </Prop3>
</SomeDocument>

但 Prop1、Prop2 和 Prop3 可能不存在。可能还有其他 XDocuments,我将使用相同的代码对其进行解析,它们具有完全不同的属性。但我只对具有 Prop1 或同时具有 Prop1 和 Prop2 的 XDocument 感兴趣。

var query = from n in xml.Elements()
where n.Name == "Prop1" || n.Name == "Prop2"
select new {n.Name, n.Value};

string prop1 = null;
string prop2 = null;

foreach (var n in query)
{
if (n.Name == "Prop1") prop1 = n.Value;
if (n.Name == "Prop2") prop2 = n.Value;
}

if (string.IsNullOrEmpty(prop1)) { //error }
if (string.IsNullOrEmpty(prop2)) { DoMethod1(prop1); }
else { DoMethod2(prop1, prop2); }

查询后的代码对我来说似乎太长了,但我不确定是否有更好的方法来完成我想做的事情。找到 1 或 2 个显式节点,并根据找到的节点(如果有)调用相关方法。

最佳答案

我个人使用:

        var element = xml.Element("prop1");
if (element!= null)
{
//The element exists, now do things on it!
if(string.IsNullOrEmpty(element.Value)) {DoMe(element.Value);}
}

如果你已经命名了你知道的属性(元素),你可以只命名它们,它将被返回。这也节省了额外的循环(至少在您的代码中)

关于c# - 我可以更好地重写这个 LINQ to XML 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2376388/

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