1

这是我的代码,它不断抛出 System.Xml.XmlException: Element 'Customer' was not found.And XML file pasteed at bottom

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,它清楚地包含 Element Customer

<?xml version="1.0" encoding="utf-8"?>
<Customers>
    <Customer>
        <FirstName>John</FirstName>
        <LastName>Smith</LastName>
        <Email>jsmith@gmail.com</Email>
    </Customer>
    <Customer>
        <FirstName>Jane</FirstName>
        <LastName>Doe</LastName>
        <Email>janedoe@yahoo.com</Email>
    </Customer>
</Customers>
4

2 回答 2

3

从文档中ReadStartElement(string)

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

当您只调用ReadToDescendant("Customers")当前节点时,将是Customers,而不是Customer

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

你真的需要使用XmlReader吗?如果您可以使用 LINQ to 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();
于 2012-04-12T21:03:29.363 回答
0

如果您想使用 ReadToDescendent,我认为您需要阅读到“客户”节点,如下所示:

// read past all nodes to the first Customer node
xmlIn.ReadToDescendant("Customer");
于 2012-04-12T21:04:58.943 回答