gpt4 book ai didi

c# - 根据Condition读取多个节点

转载 作者:行者123 更新时间:2023-11-30 22:57:03 26 4
gpt4 key购买 nike

我有以下 XML 结构。这只是一个提取文件,该文件包含“PList”下“PName”的多个节点。我刚刚在这里展示了两个作为示例。

问题是我需要提取所有分类属性值为“paymenttype”且类别属性值为“Wallet”的节点。然后从结果中提取“标题”并存储为字典或列表。一旦提取存储,这是一个列表或字典,用于比较提取的节点。

<PatientDetailsXML>             
<PList>
<PName type="Patient">
<properties>
<Room bedType="Auto" />
<PName title="Joe Beom" PId="1234">
<Details>
<classification classification="paymenttype" category="Wallet" />
<classification classification="Humor" category="None" />
<classification classification="Food" category="Fruit" />
</Details>
</PName>
</properties>
<childEvents>
</childEvents>
</PName>
<PName type="Patient">
<properties>
<Room bedType="Auto" />
<PName title="John Bair" PId="5678">
<Details>
<classification classification="paymenttype" category="Found" />
<classification classification="Humor" category="None" />
<classification classification="Food" category="Fruit" />
</Details>
</PName>
</properties>
<childEvents>
</childEvents>
</PName>
</PList>
</PatientDetailsXML>

我试过如下,但似乎做不对:

 XElement root = XElement.Load("patientdetails.xml");
IEnumerable<XElement> tests =

from el in root.Elements("PName")
where ((string)el.Element("properties").Element("PName").Element("Details").Element("classification").Attribute("paymenttype") == "EventType") && (string)el.Element("properties").Element("PName").Element("Details").Element("classification").Attribute("category") == "Wallet")

select el;



foreach (XElement el in tests)
{

Console.WriteLine (el);
}

编辑(我的第二次尝试):

XmlTextReader Readers = new XmlTextReader("patientdetails.xml");
XmlDocument docs = new XmlDocument();
docs.Load(Readers);


foreach (XmlNode n in docs.SelectNodes(@"//PName/properties/PName/Details/classification[@classification='paymenttype' and @category='Wallet']"))
{
Console.WriteLine(n.ParentNode.ParentNode.OuterXml);
}

最佳答案

我更正了您的第一次尝试 (LINQ)。它首先返回 <PName type="Patient">来自有问题的 xml。

IEnumerable<XElement> tests =
from el in root.Element("PList").Elements("PName")
let c = el.Descendants("classification")
where c.Where(x => x.Attribute("classification").Value == "paymenttype"
&& x.Attribute("category").Value == "Wallet").Any()
select el;

然后你可以迭代tests并提取您想要的内容。

foreach (var el in tests)
{
Console.WriteLine(
el.Element("properties")
.Element("PName")
.Attribute("title")
.Value);
}

我还纠正了您的第二次尝试 (XPath)。它将返回 <PName title="Joe Beom" PId="1234"> 的标题值.

var query = @"//PName[Details/classification[@classification='paymenttype' and @category='Wallet']]/@title";
foreach (XmlNode n in docs.SelectNodes(query))
{
Console.WriteLine(n.Value);
}

关于c# - 根据Condition读取多个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53881307/

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