2012-06-22 57 views
4

我真的很努力想要讓我的頭轉過來。C#linq to xml,具有屬性的嵌套查詢

我正在使用c#。

我想從一個XML文件中找回IEnumerable的產品。

下面是XML結構的樣品。

我需要的是具有設置爲如真productEnriched自定義屬性的產品列表。

有些產品不會有根本

我頭上的任何自定義屬性部分已經strated傷想到它!

<?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

我需要的產品 只是有一個定做的產品列表屬性元素用在XML productEnriched屬性和真實 一些產品的價值不會有任何自定義屬性或自定義屬性的元素 一些產品會有,但與假 值我只是需要的地方存在的產品列表一個第二有真正

<?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> 
+0

爲什麼'<自定義屬性屬性ID = 「productEnriched」>真'? (至少)''? –

+0

我必須拉出具有值爲true的嵌套自定義屬性的產品列表。我不明白爲什麼問題抱歉?我已經嘗試了所有我能想到的,讓我自己瘋狂的舞臺!即時通訊新的C#/ LINQ這不是太多幫助! – Pete

回答

3

我需要的產品清單隻顯示有與在XML productEnriched屬性和真實一些產品價值 一個 定製屬性元素的產品不會有任何的值自定義屬性或 定製屬性的元素有些產品會有,但有值的假 我只是需要的地方存在的產品清單,並具有真正

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> 
+0

謝謝你,你的明星。閱讀解決方案時看起來更容易! – Pete

+0

當我手工輸入示例時,目錄,類別的東西只是我的拼寫錯誤。 – Pete

+0

不,這不是我的檔案,我無法控制它,因此必須把它拿走。不是我會這樣做的方式,而是你必須接受的一些事情!再次感謝 – Pete