在Linq需要帮助,我需要将数据添加到列表
问题描述:
这是我的XML文件的结构。在Linq需要帮助,我需要将数据添加到列表
<Resto>
<ID>2</ID>
<Name>name</Name>
<Category>categroty</Category>
<Places>
<Address>
<Location>loc</Location>
<Number>num</Number>
<Longitude>"empty"</Longitude>
<Latitude>"empty"</Latitude>
</Address>
</Places>
</Resto>
经度和纬度是空的,我现在没有使用它们,这些用于以后的更新。 而有些人可能有超过1个地址:
<Address>
<Location>loc</Location>
<Number>num</Number>
<Longitude>"empty"</Longitude>
<Latitude>"empty"</Latitude>
</Address>
而且我这样做,查询这是工作完美的罚款:
var anything = from resto in appDataXml.Descendants("Resto")
select new limit()
{
ID = resto.Element("ID").Value,
Name = resto.Element("Name").Value,
Categories = resto.Element("Category").Value
};
我有这些的限制类:
public string Name{get;set;}
public string ID { get; set; }
public string Categories{get;set;}
public List<Address> Addresses { get; set; }
和“地址”是另一个类的位置和数字获取/设置。
无论如何,我的问题是我如何查询XML文件,并添加到地址列表的位置和数量,以便我可以将这些值添加到列表框。
非常感谢。
答
如果您使用.net版本3.5,则使用XML数据进行播放,对用户LINQ to XML更好。
http://www.codeproject.com/Articles/24376/LINQ-to-XML
或
答
var doc = XDocument.Load("test.xml");
List<Address> locations = (from address in doc.Root.Element("Places").Elements("Address")
select new Address
{
Location = address.Element("Location").Value,
Number = address.Element("Number").Value,
}).ToList();
确保你有一个根节点(如<parent>
):
<parent>
<ID>1</ID>
<Name></Name>
<Category></Category>
<Places>
<Address>
<Location></Location>
<Number></Number>
</Address>
<Address>
<Location></Location>
<Number></Number>
</Address>
</Places>
</parent>
更新: 如果您的XML看起来是这样的:
<Restos>
<Resto>
<ID>1</ID>
<Name>name</Name>
<Category>categroty</Category>
<Places>
<Address>
<Location>loc1</Location>
<Number>num1</Number>
<Longitude>"empty"</Longitude>
<Latitude>"empty"</Latitude>
</Address>
</Places>
</Resto>
<Resto>
<ID>2</ID>
<Name>name</Name>
<Category>categroty</Category>
<Places>
<Address>
<Location>loc2</Location>
<Number>num2</Number>
<Longitude>"empty"</Longitude>
<Latitude>"empty"</Latitude>
</Address>
</Places>
</Resto>
</Restos>
您可以使用此代码来分析它:
var doc = XElement.Load("test2.xml");
List<Resto> restos = (from resto in doc.Elements("Resto")
select new Resto
{
ID = resto.Element("ID").Value,
Name = resto.Element("Name").Value,
Category = resto.Element("Category").Value,
Addresses = (from address in resto.Element("Places").Elements("Address")
select new Address
{
Location = address.Element("Location").Value,
Number = address.Element("Number").Value,
}).ToList()
}).ToList();
凡Resto
和Address
被定义为:
public class Resto
{
public string ID { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public List<Address> Addresses { get; set; }
}
public class Address
{
public string Location { get; set; }
public string Number { get; set; }
}
我如你所说,但我得到了nullReferenceException。任何想法 ? – user1200204 2012-02-10 11:59:03
@ user1200204您是否将此代码应用于其他(也许更大)的xml文件?你能用更完整的xml结构来更新你的问题吗? – Meysam 2012-02-10 12:02:21
我更新了它,希望能让事情更清楚。 – user1200204 2012-02-10 12:21:57