2012-04-12 52 views
0

这是我的代码,它一直抛出异常,System.Xml.XmlException:元素'Customer'未找到。并将XML文件粘贴到底部解析XML会导致System.Xml.XmlException:找不到元素'Customer'

public static List<Customer> GetCustomers() 
{ 
    // create the list 
    List<Customer> customers = new List<Customer>(); 

    // create the XmlReaderSettings object 
    XmlReaderSettings settings = new XmlReaderSettings(); 
    settings.IgnoreWhitespace = true; 
    settings.IgnoreComments = true; 

    // create the XmlReader object 
    XmlReader xmlIn = XmlReader.Create(path, settings); 

    // read past all nodes to the first Customer node 
    xmlIn.ReadToDescendant("Customers"); 

    // create one Customer object for each Customer node 
    do 
    { 
     Customer c = new Customer(); 
     xmlIn.ReadStartElement("Customer"); 
     c.FirstName = 
      xmlIn.ReadElementContentAsString(); 
     c.LastName = 
      xmlIn.ReadElementContentAsString(); 
     c.Email = 
      xmlIn.ReadElementContentAsString(); 
     customers.Add(c); 
    } 
    while (xmlIn.ReadToNextSibling("Customer")); 

    // close the XmlReader object 
    xmlIn.Close(); 

    return customers; 

这是我的XML,它清楚地包含元素客户

<?xml version="1.0" encoding="utf-8"?> 
<Customers> 
    <Customer> 
     <FirstName>John</FirstName> 
     <LastName>Smith</LastName> 
     <Email>[email protected]</Email> 
    </Customer> 
    <Customer> 
     <FirstName>Jane</FirstName> 
     <LastName>Doe</LastName> 
     <Email>[email protected]</Email> 
    </Customer> 
</Customers> 

回答

2

从文档的ReadStartElement(string)

检查当前内容节点是具有给定名称的元素,并将阅读器推进到下一个节点。

当你只叫ReadToDescendant("Customers")当前节点将是Customers,不Customer

可以通过将其更改为ReadToDescendants("Customer")或在第一个之后添加类似的额外呼叫来修复此问题。

你真的需要使用XmlReader虽然?如果你可以使用LINQ到XML阅读你的代码将简单:

return XDocument.Load(path) 
       .Root 
       .Elements("Customer") 
       .Select(x => new Customer { 
          FirstName = (string) x.Element("FirstName"), 
          LastName = (string) x.Element("LastName"), 
          Email = (string) x.Element("Email") 
         }) 
       .ToList(); 
+0

谢谢!终于明白了,我非常沮丧。我真的需要学习LINQ。你是C#的作者吗?我读过你的书,但对我来说太过先进。 – user1125033 2012-04-12 21:37:29

+2

@ user1125033:是的,这是我的书。希望当你有更多的经验时,你会发现它更有用。是的,你*真的*应该学习LINQ。这太棒了:) – 2012-04-12 21:47:07

0

如果你想使用ReadToDescendent,我认为你需要阅读,直到“客户”节点,就像这样:

// read past all nodes to the first Customer node 
xmlIn.ReadToDescendant("Customer"); 
+0

y这就是我所做的 – user1125033 2012-04-12 21:38:08