解析 XML 会导致 System.Xml.XmlException:找不到元素“客户”
本文关键字:找不到 元素 客户 XmlException Xml XML System 解析 | 更新日期: 2023-09-27 18:30:50
这是我的代码,它不断抛出系统.Xml.XmlException:找不到元素"客户"的异常。和XML文件粘贴在底部
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>jsmith@gmail.com</Email>
</Customer>
<Customer>
<FirstName>Jane</FirstName>
<LastName>Doe</LastName>
<Email>janedoe@yahoo.com</Email>
</Customer>
</Customers>
来自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();
如果你想
使用ReadToDescendent,我认为你需要读到"客户"节点,如下所示:
// read past all nodes to the first Customer node
xmlIn.ReadToDescendant("Customer");