0

我有以下 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 的方法吗?

4

1 回答 1

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),
                                           .... }
                 };
于 2013-06-13T22:22:44.430 回答