尝试使用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 ????
}
答案 0 :(得分:2)
答案 1 :(得分: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();