1

尝试使用 Linq to XML 读取此 xml

<Root>
    <shelves>
        <bookNumber>12</bookNumber>
        <coverType unit="H">soft</coverType>
        <pages>100</pages>
        <Weight units="lb">1.2</Weight>
        <chapter sample="1">example 1</<chapter>
        <chapter sample="2">example 2</<chapter>
        <chapter sample="3">example 3</<chapter>
        <chapter sample="4">example 4</<chapter>
        <chapter sample="5">example 5</<chapter>
        <chapter sample="6">example 6</<chapter>
        <chapter sample="7">example 7</<chapter>
        <chapter .................</chapter>
        <chapter .................</chapter>
        <chapter .................</chapter>
        <chapter .................</chapter>
        <chapter .................</chapter>
        ..............
    </shelves>
</Root>

那就是我正在尝试的代码:-。但是如何读取所有元素'Chapter'的值?

var book = from b in xml.Root.Elements("shelves")
                             select b;
    foreach (var s in book)
    {
        booknumber = s.Element("bookNumber").Value,
        covertype = s.Element("bookNumber").Value,
        coverTypeUnit = s.Element("bookNumber").Attribute("unit").Value,
        ...........
        chapter = s.Element("bookNumber").Value ????
    }
4

2 回答 2

2

您可能会发现这些链接很有用:

linq-to-read-xml

101 个 LINQ 示例

于 2012-12-18T15:26:18.010 回答
1
var values = s.Elements("chapter").Select(n => n.Value).ToArray();

此外,您一遍又一遍地阅读同一个元素(书号)。您可能想检查您的代码。

编辑:也产生属性:

s.Elements("chapter").
Select(n => new {Topic = n.Attribute("topic").Value, Value = n.Value}).
ToArray();
于 2012-12-18T15:26:08.683 回答