2013-07-10 54 views
-3

的名单我有一个XML是高达20 MB:阅读高达20 MB大小的XML并将其分配给

<Neighborhood> 
<Code LocationID='27767' NeighborhoodName='Broadway-Times Square' Latitude='40.7586' Longitude='-73.988152'/> 
<Code LocationID='27767' NeighborhoodName='Midtown East' Latitude='40.755645' Longitude='-73.967428'/> 
</Neighborhood> 

我想读取XML和创建类的列表。

类如下:

public class HotelNeighbourhood 
{ 
    public int LocationID { get; set; } 
    public string NeighborhoodName { get; set; } 
    public float Latitude { get; set; } 
    public float Longitude { get; set; } 
} 

我想在最快的方式创建一个列表。 在此先感谢。

+0

下一次,请格式化更敏感。 –

+2

有关您编写的代码问题的问题必须描述特定的问题并包含有效的代码以进行重现。请参阅[SSCCE.org](http://sscce.org/)获取指导。 – DGibbs

+0

请阅读:http://stackoverflow.com/questions/12931769/c-sharp-and-reading-large-xml-files和http://stackoverflow.com/questions/7671958/reading-large-xml-documents- in-net和http://stackoverflow.com/questions/468948/in-c-sharp-what-is-the-best-way-to-parse-large-xml-size-of-1gb – Sabilv

回答

0

这是你想要

var query = (from n in xml.Descendants("Code") 
       select new HotelNeighbourhood() 
       { 
        LocationID = Convert.ToInt32(n.Attribute("LocationID").Value), 
        NeighborhoodName = n.Attribute("NeighborhoodName").Value, 
        Longitude = float.Parse(n.Attribute("Longitude").Value), 
        Latitude = float.Parse(n.Attribute("Latitude").Value) 

       }).ToList(); 

会给你一个List<HotelNeighborhood>什么。

0

您应该搜索XmlReader类的用法。这是获取对XML文件的只读访问权的最快方式,特别是当文件很大时。它在当时读取一个元素,因此您不需要一次加载整个文档。

你也可以检查LINQ to XML。它更适合开发人员,但不幸的是需要将整个XML加载到内存中,当文件很大时可能会导致问题。

1

看看this,这将工作,而不知道如果它是最快的方法。

+1

+1。我怎么能忘记序列化... – MarcinJuraszek

+3

比忘记Dre更好。 –

0

reader = new XmlTextReader(_XMLUrlPath +“indexNeighbourhood.xml”); 而(reader.Read()){ 如果 (reader.NodeType == XmlNodeType.Element & & reader.Name == “代码”) { HotelNeighbourhood hotelNeighbourhood =新HotelNeighbourhood(); hotelNeighbourhood.LocationID = int.Parse(reader.GetAttribute(“LocationID”)。ToString()); hotelNeighbourhood.NeighborhoodName = reader.GetAttribute(“NeighborhoodName”)。ToString(); hotelNeighbourhood.Latitude = reader.GetAttribute(“Latitude”)。ToString()!= string.Empty? float.Parse(reader.GetAttribute(“Latitude”)。ToString()):0; hotelNeighbourhood.Longitude = reader.GetAttribute(“Longitude”)。ToString()!= string.Empty? float.Parse(reader.GetAttribute(“Longitude”)。ToString()):0; LstHNeighbourHood.Add(hotelNeighbourhood); } } reader.Close(); reader = null; 路径

相关问题