如何在数组C#中存储xml节点

时间:2016-10-26 03:11:36

标签: c# xml

我有一个像这样的xml文档

<UpdateDefinition>
      <manufacturer>Newton Cars, Inc</manufacturer>
      <model>Newton1</model>
      <model>Newton2</model>
      <model>Newton3</model>
      <model>Newton4</model>
      <fwversion>A.02.14</fwversion>
      <description>Newton cars NOTE: Media LCD display may go blank for about 30 seconds on first reboot.</description>
      <notes>Refer to release notes.</notes>
      <date>4/25/2013</date>
      <md5hash>N6/DsMDwkkU4bCeQ3aPQWg==</md5hash>
</UpdateDefinition>

我应该从上面的xml中提取信息并将其保存在一个数组中以供将来比较使用。 知道怎么样?

2 个答案:

答案 0 :(得分:0)

试试这个:

var xd = XDocument.Parse(@"<UpdateDefinition>
      <manufacturer>Newton Cars, Inc</manufacturer>
      <model>Newton1</model>
      <model>Newton2</model>
      <model>Newton3</model>
      <model>Newton4</model>
      <fwversion>A.02.14</fwversion>
      <description>Newton cars NOTE: Media LCD display may go blank for about 30 seconds on first reboot.</description>
      <notes>Refer to release notes.</notes>
      <date>4/25/2013</date>
      <md5hash>N6/DsMDwkkU4bCeQ3aPQWg==</md5hash>
</UpdateDefinition>");

string[] models = xd.Root.Descendants("model").Select(xe => xe.Value).ToArray();

我明白了:

models

答案 1 :(得分:0)

您可能对Xml.Linq感兴趣:

XDocument doc = XDocument.Load(yourXMLFile);
var aa = doc.Descendants("UpdateDefinition").Select(d => new
{
    manufacturer = d.Element("manufacturer").Value,
    models = d.Elements("model").Select(e => e.Value).ToList(),
    fwversion = d.Element("fwversion").Value,
    description = d.Element("description").Value,
    notes = d.Element("notes").Value,
    date = d.Element("date").Value,
    md5hash = d.Element("md5hash").Value
}).ToList();

它将为您提供所有值和模型列表。