我正在尝试XDocument
使用实例解析数据Linq to XML
并将其存储在IEnumerable<MyClass>
. 我不想从 xml 文档中获取每个元素,所以我使用ElementAt(#index)
它来获取值。但是有时我想要的元素不在文档中,然后我得到索引超出范围异常。有没有更好的方法来解析这个文档中的值?这是代码:
XML 文档如下所示:
<someotherelement> /* I dont want the "someotherelement" part either */
<subelement></subelement>
<subelement></subelement>
</someotherelement>
<result>
<doc>
<int name="personid">8394</int> /* I don't want this value so I am skipping it */
<str name="name">James</str>
<str name="address">30 Awesome Lane</str>
<arr name="randomearray"> /* I want to skip this too */
<str name="random1">SomeValue</str>
<str name="random2">SomeValue</str>
<str name="random2">SomeValue</str>
</arr>
<str name="city">Awesome City</str>
<str name="state">CA</str>
<int name="zipcode">84392</int>
<str name="country">USA</str>
<str name="phonenumber">8309933820</str>
<date name="reportdate">2012-07-27T06:01:05.256Z</date>
</doc>
/* This is missing address and country */
<doc>
<int name="personid">10394</int> /* I don't want this value so I am skipping it */
<str name="name">Mathew</str>
<arr name="randomearray"> /* I want to skip this too */
<str name="random1">SomeValue</str>
<str name="random2">SomeValue</str>
<str name="random2">SomeValue</str>
</arr>
<str name="city">Not Awesome City</str>
<str name="state">CA</str>
<str name="zipcode">58439</str>
<str name="phonenumber">8309933820</str>
<date name="reportdate">2012-07-27T06:01:05.256Z</date>
</doc>
</result>
班级:
public class Doc
{
public string Name {get;set;}
public string Address{get;set;}
public string City {get;set;}
public string State {get;set;}
public int ZipCode {get;set;}
public string Country {get;set;}
public string PhoneNumber {get;set;}
public DateTime ReportDate {get;set;}
}
链接到 XML
string pathToXml = "http://www.foo.com/something";
var doc = XDocument.Load(pathToXml);
IEnumerable<Doc> myDoc = from item in doc.Descendants("doc")
select new Doc
{
Name = item.Element("str").Value,
Address = item.Element("str").ElementsAfterSelf("str").First().Value,
City = item.Element("str").ElementsAfterSelf("str").ElementAt(1).Value,
State = item.Element("str").ElementsAfterSelf("str").ElementAt(2).Value,
ZipCode = Convert.ToInt32(item.Element("int").Value)
Country = item.Element("str").ElementsAfterSelf("str").ElementAt(3).Value,
PhoneNumber = item.Element("str").ElementsAfterSelf("str").ElementAt(4).Value,
ReportDate = Convert.ToDateTime(item.Element("date").Value)
};