使用linq读取xml文件并获取错误:给定编码中的字符无效

时间:2015-07-19 10:13:23

标签: c# xml linq

这样我用linq读取xml文件并得到错误Invalid character in the given encoding

XDocument document = XDocument.Load(@"c:\users\tridip\documents\visual studio 2010\Projects\WindowsFormsApplication5\WindowsFormsApplication5\Orders.xml");
            var books = from r in document.Descendants("book")
            select new
            {
                OrderID = r.Element("OrderID").Value,
                CustomerID = r.Element("CustomerID").Value,
                EmployeeID = r.Element("EmployeeID").Value,
            };

我在xml中看到了这种数据

<Orders>
    <OrderID>10249</OrderID>
    <CustomerID>TOMSP</CustomerID>
    <EmployeeID>6</EmployeeID>
    <OrderDate>1996-07-05T00:00:00</OrderDate>
    <RequiredDate>1996-08-16T00:00:00</RequiredDate>
    <ShippedDate>1996-07-10T00:00:00</ShippedDate>
    <ShipVia>1</ShipVia>
    <Freight>11.6100</Freight>
    <ShipName>Toms Spezialitäten</ShipName>
    <ShipAddress>Luisenstr. 48</ShipAddress>
    <ShipCity>Münster</ShipCity>
    <ShipPostalCode>44087</ShipPostalCode>
    <ShipCountry>Germany</ShipCountry>
  </Orders>

请参阅此<ShipName>Toms Spezialitäten</ShipName>文字中有一些无效或未知的字符。如何摆脱这个。如果xml数据中存在未知字符,我想读取xml。请指导我在上面的代码中添加什么来处理这种情况。感谢

问题解决了

我在xml数据中添加编码的那一刻,就像它开始工作一样

<?xml version="1.0" encoding="utf-8"?>
<Root>
  <Orders>
    <OrderID>10248</OrderID>
    <CustomerID>VINET</CustomerID>
    <EmployeeID>5</EmployeeID>
    <OrderDate>1996-07-04T00:00:00</OrderDate>
    <RequiredDate>1996-08-01T00:00:00</RequiredDate>
    <ShippedDate>1996-07-16T00:00:00</ShippedDate>
    <ShipVia>3</ShipVia>
    <Freight>32.3800</Freight>
    <ShipName>Vins et alcools Chevalier</ShipName>
    <ShipAddress>59 rue de l'Abbaye</ShipAddress>
    <ShipCity>Reims</ShipCity>
    <ShipPostalCode>51100</ShipPostalCode>
    <ShipCountry>France</ShipCountry>
  </Orders>

<Orders>
   .... more data
</Orders>
</Root>

private void button1_Click(object sender, EventArgs e)
        {
            XDocument document = XDocument.Load(@"c:\users\tridip\documents\visual studio 2010\Projects\WindowsFormsApplication5\WindowsFormsApplication5\Orders.xml");
            var books = from r in document.Descendants("Orders")
            select new
            {
                OrderID = r.Element("OrderID").Value,
                CustomerID = r.Element("CustomerID").Value,
                EmployeeID = r.Element("EmployeeID").Value,
            };

          dataGridView1.DataSource=  books.ToList();
        }

0 个答案:

没有答案