读取XML并保存到Excel C#

问题描述:

我有XML如下,我需要读取此XML并获取XML中的特定元素并保存到Excel中。 下面是我的XML文件:读取XML并保存到Excel C#

<?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> 

下面是预期的结果: Expected Result

任何人都可以指导我在此。

+0

这看起来像打开excel文件。你想只提取一部分xml并保存为excel? – jdweng

+0

是的,我想提取一部分xml并保存为excel – ctee

试试这个解析文件。你仍然需要保存为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(); 

     } 

    } 

} 
+0

谢谢!它的工作对我来说很好。 – ctee