C# - 仅从父节点解析子节点属性值

时间:2013-12-07 07:35:51

标签: c# xml

假设我们有以下XML文件,看起来像

<model uri="model1">
  <PriceData>
    <value price="24.28" date="2013-12-01"/>
    <value price="22.34" date="2013-12-02"/>
    <value price="24.12" date="2013-12-03"/>
 </PriceData>
</model>
<model uri="model2">
  <PriceData>
    <value price="24.28" date="2013-12-01"/>
    <value price="22.34" date="2013-12-02"/>
    <value price="24.12" date="2013-12-03"/>
 </PriceData>
</model>

这可以继续许多型号和价格。我搜索一种方法,在不同的列表(或数组)中解析每个模型的价格而不用手动,即预分配列表等,因为模型的数量不会一直相同。那么我怎样才能为不同型号制作价格“桶”呢?我到现在为止尝试的是

using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Collections.Generic;

namespace test
{
   class Program
   {
       static void Main(string[] args)
       {
          string file = @"C:\Users\user\Desktop\test.xml";
          XDocument doc = XDocument.Load(file);
          List<string> priceData = new List<string>();
          List<string> modelName = new List<string>();
          foreach (var imovel in doc.Root.Descendants("model"))
          {
             modelName.Add(imovel.Attribute("uri").Value);
          }
          int modelNum = modelName.Count();
          foreach (var item in doc.Descendants("value"))
          {
               var doubleAttr = item.Attribute("price");
               if (doubleAttr == null) continue;
               priceData.Add(item.Attribute("price").Value);
          }            
          //Console.WriteLine(modelName[0]);
          Console.ReadKey();
       }
   }
}

但在这种情况下,第二个foreach循环获取列表中所有模型的价格。我试着想出一些想法......我的咖啡是空的: - (

2 个答案:

答案 0 :(得分:1)

尝试LINQ:

string file = @"C:\Users\user\Desktop\test.xml";
XDocument doc = XDocument.Load(file);

XDocument doc = XDocument.Parse(file);
var list = doc.Elements("model").Select(x => new {
    Uri = x.Attribute("uri").Value,
    Prices = x.Element("PriceData").Elements().Select(y => new {
        Price = y.Attribute("price"),
        Date = y.Attribute("date")
    }).ToList()
}).ToList();

这是小提琴:http://dotnetfiddle.net/QbtKgo

但实际上这段代码可能与您的xml架构有所不同,但它显示了这种方法。

答案 1 :(得分:0)

所以我找到了一个解决方案,它给了我正在寻找的结果

  string file = @"C:\Users\user\Desktop\test.xml";
  string id = "model1"; /* here you can set a parse dialog*/  
  string ModelID = "//model[@uri='" + id + "']";
  List<string> priceData = new List<string>();
  XmlDocument xDoc = new XmlDocument();
  xDoc.Load(file);
  XmlNodeList PriceNodeList = xDoc.SelectNodes(ModelID + "/PriceData/value");

  //looping through the all the node details one by one          
   foreach (XmlNode x in PriceNodeList)
   {
   //for the current Node retrieving all the Attributes details            
   var price = x.Attributes["double"];
   if (price == null) continue;
   priceData.Add(price.Value);
   }
相关问题