gpt4 book ai didi

c# - Linq XML 使用属性中的特定值查询父级的后代

转载 作者:行者123 更新时间:2023-12-04 10:47:19 25 4
gpt4 key购买 nike

我需要一些 LINQ to XML 方面的帮助。我有以下 XML;

<GcctTestData>
<TestDriveRequest Record="1">
<element name="Time Zone">(GMT+05:30)</element>
<element name="Requested Dealer">Concorde</element>
<element name="Model Year">1999</element>
<element name="Make">Tata</element>
<element name="Model/Vehicle Line">Indica</element>
</TestDriveRequest>
<TestDriveRequest Record="2">
<element name="Time Zone">(GMT+05:30)</element>
<element name="Requested Dealer">Kun"</element>
<element name="Model Year">2020"</element>
<element name="Make">BMW"</element>
<element name="Model/Vehicle Line">3-series</element>
</TestDriveRequest>
<TestDriveRequest Record="3">
<element name="Time Zone">(GMT+05:30)</element>
<element name="Requested Dealer">KUN Hyundai</element>
<element name="Model Year">2001</element>
<element name="Make">Hyundai</element>
<element name="Model/Vehicle Line">Verna</element>
</TestDriveRequest>
</GcctTestData>

我试过如下:
IEnumerable<XElement> xElements =
from element in root.Elements("TestDriveRequest")
where element.Attribute("Record").Value == "1"
select element;

foreach (XElement el in xElements.Descendants().Where(p => !p.HasElements))
{
int keyInt = 0;
string keyName = el.Attribute("name").Value;

while (keyValuePairs.ContainsKey(keyName))
{
keyName = $"{el.Attribute("name").Value}_{keyInt++}";
}
keyValuePairs.Add(keyName, el.Value);
}

我必须得到元素 姓名 的属性值元素 对于具有记录值 的父级1

但是 linq 查询没有获取它......

在实现@anu-viswan 的建议后,我面临以下问题
enter image description here

最佳答案

您需要使用 root.Descendants而不是 root.Elements .

例如,

IEnumerable<XElement> xElements =   from element in root.Descendants("TestDriveRequest")
where element.Attribute("Record").Value == "1"
select element;

XContainer.Elements

Returns a filtered collection of the child elements of this element or document, in document order. Only elements that have a matching XName are included in the collection.



XContainer.Descendants

Returns a filtered collection of the descendant elements for this document or element, in document order. Only elements that have a matching XName are included in the collection Output



完整代码
IEnumerable<XElement> xElements =   from element in root.Descendants("TestDriveRequest")
where element.Attribute("Record").Value == "1"
select element;

foreach (XElement el in xElements.Descendants().Where(p => !p.HasElements))
{
int keyInt = 0;
string keyName = el.Attribute("name").Value;

while (keyValuePairs.ContainsKey(keyName))
{
keyName = $"{el.Attribute("name").Value}_{keyInt++}";
}
keyValuePairs.Add(keyName, el.Value);
}

样本输出

enter image description here

关于c# - Linq XML 使用属性中的特定值查询父级的后代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59643060/

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