读取XML并保存到Excel C#

我有XML如下,我需要阅读这个XML,并在XML中获取特定的元素,并保存到Excel中。 以下是我的XML文件:

<?xml version="1.0" encoding="UTF-8"?> <ns1:BookTestXMLExport StartTime="2016-09-20T12:58:15.000+07:00" scanTime="2016-09-20T12:58:15.000+07:00" scanStatus="Pass"> <ns1:MachineXML barCode="ISN-1000500213" Revision="2016A" bookType="Novel"/> <ns1:StationXML scannerName="HP4512745" stage="v810"/> <ns1:ScanXML name="32:2:165:1"> <ns1:IndictmentXML algorithm="NIL" subType="17X8X15MM" imageFileName="175228000_9_0.jpg"> <ns1:BorrowXML packageId="NIL" userId="NIL" name="NIL"/> <ns1:BookXML name="GrayDay" desc="Love Story"/> </ns1:IndictmentXML> </ns1:ScanXML> <ns1:ScanXML name="35:23:165:1"> <ns1:IndictmentXML algorithm="NIL" subType="17X8X15MM" imageFileName="175228001_9_0.jpg"> <ns1:BorrowXML packageId="NIL" userId="8799" name="Sharon"/> <ns1:BookXML name="Harry Potter" desc="Magic"/> </ns1:IndictmentXML> </ns1:ScanXML> </ns1:BookTestXMLExport> 

以下是预期结果: 预期结果

任何人都可以指导我这个。

试试这个parsing文件。 你仍然需要保存为Excel。

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; namespace ConsoleApplication14 { class Program { const string FILENAME = @"c:\temp\test.xml"; static void Main(string[] args) { XDocument doc = XDocument.Load(FILENAME); XElement bookTestXMLExport = doc.Descendants().Where(x => x.Name.LocalName == "BookTestXMLExport").FirstOrDefault(); XNamespace ns = bookTestXMLExport.GetNamespaceOfPrefix("ns1"); var results = doc.Descendants(ns + "BookTestXMLExport").Select(x => new { scanStatus = (string)x.Attribute("scanStatus"), barCode = (string)x.Element(ns + "MachineXML").Attribute("barCode"), ScanXML = x.Elements(ns + "ScanXML").Select( y => new { name = (string)y.Descendants(ns + "BookXML").FirstOrDefault().Attribute("name"), desc = (string)y.Descendants(ns + "BookXML").FirstOrDefault().Attribute("desc") }).ToList() }).ToList(); } } }