C# 在XML的内部元素中使用where条件
我正在尝试解析一个XML文档,并使用C#中的LINQ将数据存储在一个数组中,其中我有多个具有不同数据的内部元素,它们的属性具有相同的名称,看起来像C# 在XML的内部元素中使用where条件,c#,xml,linq,C#,Xml,Linq,我正在尝试解析一个XML文档,并使用C#中的LINQ将数据存储在一个数组中,其中我有多个具有不同数据的内部元素,它们的属性具有相同的名称,看起来像 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Catalog> <Book ISBN="1.1.1.1" Genre="Thriller"> <Title PublishDt="2015-07-09"> <Pty R
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Catalog>
<Book ISBN="1.1.1.1" Genre="Thriller">
<Title PublishDt="2015-07-09">
<Pty R="1" ID="Buyer_Company">
</Pty>
<Pty R="2" ID="Seller_Company">
</Pty>
</Title>
</Book>
</Catalog>
我可以知道如何在
C#
中使用WHERE
的内部元素和XML
的属性中使用WHERE
条件,这样R=1代表买方,R=2代表卖方吗?如果在那里应用WHERE
子句,那么您将再次获得IEnumerable
,并且从中您可以必须选择一个卖方\买方或获取卖方\买方数组。我认为买方和卖方只有两个节点,因此查询为:-
var result = doc.Descendants("Book")
.Select(b =>
{
var buyerNode = b.Element("Title").Elements("Pty")
.First(x => x.Attribute("R").Value == "1");
var sellerNode = b.Element("Title").Elements("Pty")
.First(x => x.Attribute("R").Value == "2");
return new
{
ISBN = b.Attribute("ISBN").Value,
Genre = b.Attribute("Genre").Value,
PublishDate = b.Element("Title").Attribute("PublishDt").Value,
Buy = buyerNode.Attribute("ID").Value,
Sell = sellerNode.Attribute("ID").Value,
};
}
).ToArray();
另外,请注意,您需要
元素
而不是元素
来获取多个Pty
节点。您需要按顺序思考。您需要查询所有Pty
元素,然后根据R
属性值对它们进行过滤,然后获得所需的属性
因此,您的买家id可以通过以下方式获得:
b.Descendants("Pty")
.Where(e => (int)e.Attribute("R") == 1)
.Select(e => (string)e.Attribute("ID"))
.Single();
以及类似的卖家id查询(将1
更改为2
)。把这些放在一起,你可能会得到这样的结果。我将强制转换移到表达式的开头,以便更清楚地了解属性的类型
var result = from book in doc.Descendants("Book")
select new
{
ISBN = (string)book.Attribute("ISBN"),
Genre = (string)book.Attribute("Genre"),
PublishDate = (DateTime)book.Elements("Title")
.Select(e => e.Attribute("PublishDt"))
.Single(),
Buyer = (string)book.Descendants("Pty")
.Where(e => (int)e.Attribute("R") == 1)
.Select(e => e.Attribute("ID"))
.Single(),
Seller = (string)book.Descendants("Pty")
.Where(e => (int)e.Attribute("R") == 2)
.Select(e => e.Attribute("ID"))
.Single()
};
var result = from book in doc.Descendants("Book")
select new
{
ISBN = (string)book.Attribute("ISBN"),
Genre = (string)book.Attribute("Genre"),
PublishDate = (DateTime)book.Elements("Title")
.Select(e => e.Attribute("PublishDt"))
.Single(),
Buyer = (string)book.Descendants("Pty")
.Where(e => (int)e.Attribute("R") == 1)
.Select(e => e.Attribute("ID"))
.Single(),
Seller = (string)book.Descendants("Pty")
.Where(e => (int)e.Attribute("R") == 2)
.Select(e => e.Attribute("ID"))
.Single()
};