我真的很难弄清楚这件事。
我正在使用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>发布于 2012-06-22 18:21:46
我需要获取产品列表只需要具有属性为productEnriched且值为true的自定义属性元素的产品xml中的一些产品不会具有任何自定义属性或自定义属性元素某些产品将具有该元素,但值为false时,我只需要存在且值为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"));顺便说一下,您的category无效-您的开始标记(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>https://stackoverflow.com/questions/11154229
复制相似问题