使用Linq查询名称相同的XML元素

时间:2013-06-13 22:18:12

标签: c# linq-to-xml

我有以下XML:

<?xml version="1.0" encoding="UTF-8"?>
<ProductTypes>
    <ProductType Name="MyProduct">
        <Amount>100</Amount>
        <Pattern Length="1" AllowedCharacters="ABCD"/>
        <Pattern Length="7" AllowedCharacters="EFGH"/>
    </ProductType>
</ProductTypes>

使用Linq to XML我可以成功地从任意数量的元素ProductType中提取信息。但是,我还需要来自所有元素Pattern的信息。

        XElement xml = XElement.Load("pattern_config.xml");

        var productTypes = from productType in xml.Elements("ProductType")
                           select new {
                               Name = productType.Attribute("Name").Value,
                               Amount = Convert.ToInt32(productType.Element("Amount").Value)
                               // How to get all Pattern elements from that ProductType?
                           };

我该怎么做?或者您会建议另一种方式来访问这个XML吗?

1 个答案:

答案 0 :(得分:1)

您可以嵌套查询。

 var productTypes = from productType in xml.Elements("ProductType")
                select new {
                   Name = productType.Attribute("Name").Value,
                   Amount = Convert.ToInt32(productType.Element("Amount").Value),
                   // How to get all Pattern elements from that ProductType?
                   Patterns = from patt in productType.Elements("Pattern")
                              select new { Length = int.Parse(patt.Attribute("Length").Value),
                                           .... }
                 };