簡體   English   中英

C#linq to xml,帶屬性的嵌套查詢

[英]C# linq to xml, nested query with attributes

我真的很難想到這個問題。

我用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中的某些產品不會有任何自定義屬性或自定義屬性元素,某些產品將擁有它但具有值我只需要一個存在的產品列表,其值為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>

我需要獲得產品列表,只有具有屬性productEnriched屬性的自定義屬性元素的產品和值為true的xml中的某些產品不會有任何自定義屬性或自定義屬性元素,某些產品將擁有它但具有值我只需要一個存在的產品列表,其值為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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM