gpt4 book ai didi

C# linq to xml,带属性的嵌套查询

转载 作者:数据小太阳 更新时间:2023-10-29 02:09:00 26 4
gpt4 key购买 nike

我真的很难理解这个问题。

我正在使用 C#。

我想从 xml 文件中取回产品的 IEnumerable。

下面是 xml 结构的示例。

我需要获取将 productEnriched 自定义属性设置为 true 的产品列表。

有些产品根本没有任何自定义属性部分

光是想想我的头就疼!

<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="http://www.mynamespace.com" catalog-id="MvgCatalog">
<product>
<custom-attributes>
<custom-attribute attribute-id="productEnriched">true</custom-attribute>
</custom-attributes>
</product>
</category>

谢谢你的帮助

为了解决问题,我在示例 xml 中添加了更多项目

我需要获取产品列表只有具有属性 productEnriched 且值为 true 的自定义属性元素的产品xml 中的一些产品不会有任何自定义属性或自定义属性元素有些产品会有它,但值为 false我只需要一个存在且值为 true 的产品列表

<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="http://www.mynamespace.com" catalog-id="MvgCatalog">
<product>
<upc>000000000000</upc>
<productTitle>My product name</productTitle>
<custom-attributes>
<custom-attribute attribute-id="productEnriched">true</custom-attribute>
<custom-attribute attribute-id="somethingElse">4</custom-attribute>
<custom-attribute attribute-id="anotherThing">otherdata</custom-attribute>
</custom-attributes>
</product>
</category>

最佳答案

I need to get a list of products only products that have a custom-attribute element with the attribute productEnriched and value of true some products in the xml wont have any custom-attribute or custom-attributes elements some products will have it but with a value of false i just need a list of products where it exists and has a value of true

var xml = XElement.Load(@"your file.xml");
XNamespace ns = "http://www.mynamespace.com";
var products = xml.Elements(ns + "product");
var filtered = products.Where(
product =>
product.Element(ns + "custom-attributes") != null &&
product.Element(ns + "custom-attributes").Elements(ns + "custom-attribute")
.Any(
ca =>
ca.Value == "true" &&
ca.Attribute("attribute-id") != null &&
ca.Attribute("attribute-id").Value == "productEnriched"));

顺便说一下,您的 XML 无效 - 您的开始标记 (catalog) 与结束标记 (category) 不匹配。

格式本身很奇怪 - 这是你的主意吗?

    <custom-attributes>
<custom-attribute attribute-id="productEnriched">true</custom-attribute>
<custom-attribute attribute-id="somethingElse">4</custom-attribute>
<custom-attribute attribute-id="anotherThing">otherdata</custom-attribute>
</custom-attributes>

为什么把属性名作为属性值,属性值作为元素值呢?它看起来很臃肿,有点像没有明确目的的“重新发明”XML。

为什么不呢:

    <custom-attributes>
<custom-attribute productEnriched="true"/>
<custom-attribute somethingElse="4"/>
<custom-attribute anotherThing="otherdata"/>
</custom-attributes>

或者:

    <custom-attributes productEnriched="true" somethingElse="4" anotherThing="otherdata"/>

或者也许只是使用元素:

    <product-parameters>
<productEnriched>true</productEnriched>
<somethingElse>4</somethingElse>
<anotherThing>otherdata</anotherThing>
</product-parameters>

关于C# linq to xml,带属性的嵌套查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11154229/

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